我正在尝试检查变量是否存在,但是在函数内部。 我被告知,要做到这一点,您唯一需要做的就是:
'a' in locals()
不幸的是,事实证明事情比我预期的要困难一些。
我试图定义一个包含此方法的函数。
q=[1,2,3]
def f():
print('q' in locals())
运行此函数时,它将返回:
False
问题是,正如我们所看到的,q是一个变量,所以当我运行相同的命令但在函数之外时:
'q' in locals()
它返回:
True
有没有办法解决这个问题?
答案 0 :(得分:0)
编写以下代码行
var proxyTimer = null;
var sendTimeLimit = 1;//sec
var sessionTime = sendTimeLimit * 1000;
$(function () {
var myProxy = $.connection.myHub;
$.connection.hub.start().done(function () {
registerServerEvents(myProxy);
});
clientMethods(myProxy);
});
function registerServerEvents(proxyHub) {
proxyHub.server.connect();
$(document).on("click", "#btnHub", function (e) {
$("#hubStatus").html("Sending..");
$("#btnHub").text("Count Down Start...");
//Logic Before start sending data.
var id = 1;
var name = "AzR";
proxyHub.server.startSendingServer(id,name);
// $.connection.hub.disconnected(function () {
// setTimeout(function () { $.connection.hub.start(); }, 5000); // Restart connection after 5 seconds.
//});
$.connection.hub.disconnected(function () {
$("#hubStatus").html("Disconnected");// you can restart on here.
$("#btnHub").text("Stat Again after reload window");
});
});
}
function clientMethods(proxyHub) {
//proxyHub.on('onConnected', function (sendTimeLimit) {
// sendTimeLimit = sendTimeLimit;
//});
proxyHub.on('onNewUserConnected', function (serverItem) {
sendTimeLimit = serverItem;
sessionTime = sendTimeLimit * 1000;
});
proxyHub.on('startSendingClient', function (serverItem) {
//Logic after start sending data.
var name = serverItem.name;
var status = serverItem.status;
$("#hubStatus").html(status);
$("#counter").html(sendTimeLimit);
timeCounter();
startTimer(proxyHub, name );
});
proxyHub.on('forceStopClint', function (serverItem) {
clearClintPendingTask(serverItem);//Logic before proxy stop.
$("#btnHub").text("Force Stop...");
$.connection.hub.stop();
});
proxyHub.on('onUserDisconnected', function (serverItem) {
//Logic after proxy Disconnected (time out).
$("#hubStatus").html(serverItem);
$("#btnHub").text("Stat Again after reload window");
});
}
//Logic before proxy stop.
function clearClintPendingTask(status) {
//do all you need
$("#hubStatus").html(status);
stopTimer();
}
function startTimer(proxyHub,data) {
stopTimer();
proxyTimer = setTimeout(function () {
proxyHub.server.forceStopServer(data);
}, sessionTime);
}
function stopTimer() {
if (proxyTimer) {
clearTimeout(proxyTimer);
proxyTimer = null;
}
}
function timeCounter() {
var counter = sendTimeLimit;
var interval = setInterval(function () {
counter--;
$("#counter").html(counter);
if (counter == 0) {
//Do something
$("#counter").html("Countdown ended!");
// Stop the counter
clearInterval(interval);
}
}, 1000);
}
这里,变量'q'不是函数f()的局部变量,因为它是在函数范围之外声明的。在函数内部,可以使用global访问q。 但是,在函数“ q”之外是局部变量。 因此,当您检查函数内部
q=[1,2,3]
def f():
print('q' in locals())
f()
它将返回False
但是,如果您在函数内部声明并进行如下检查:-
q=[1,2,3]
def f():
print('q' in locals())
由于q现在位于函数本地,它将返回True。
此外,如果您在函数内部将“ q”检查为全局值,则将返回True,因为在函数外部声明了“ q”并且具有全局范围。
def f():
q=[1,2,3]
print('q' in locals())
输出
q=[1,2,3]
def f():
print('q' in globals())
f()
答案 1 :(得分:0)
您可以在q
字典中测试列表globals()
的存在,因为它存在于全局范围内,而不是函数f
的本地范围内,即:>
def f():
print('q' in globals())
正如评论中指出的那样,使用像这样的字符串名称测试变量的存在并不理想,您可以改为使用try / except:
def f():
try:
# Do something with q
print(q)
except NameError:
print("Variable not defined")
答案 2 :(得分:-2)
您可以使用
hasattr(obj, "var")
并将obj替换为self
class test():
def __init__(self):
self.a = 1
def check(self, var):
return hasattr(self, var)
t = test()
print(t.check("a"))
print(t.check("b"))
输出
True
False