这是一个相关问题:How do I check if a variable exists?
但是,它对于静态变量效果不佳。
我正在尝试执行以下操作,
class A:
def __init__(self):
if A.var is null: # this does not work, okay
A.var = 'foo'
print 'assigned'
好的,因为 A.var
甚至还没有被分配。它会引发错误。所以,我尝试了这个:
class A:
def __init__(self):
if 'A.var' not in globals(): # this seems to okay, but ..
A.var = 'foo'
print 'assigned'
a = A()
b = A()
结果:
assigned
assigned
这表明 if 'A.var' not in globals():
行无法正常工作。
那么,如何检查 Python 中是否存在静态变量?
最佳答案
要么使用 hasattr
:
if not hasattr(A, 'var'):
A.var = 'foo'
或者,正如有些人所希望的那样,根据“请求宽恕比请求许可更容易”的原则:
try:
A.var
except NameError:
A.var = 'foo'
最后,您可以简单地在类主体中定义默认值:
class A(object):
var = None
...
if A.var is None:
a.var = 'foo'
(请注意,这两种方法都不是线程安全的)
关于python - Python 中如何检查静态变量是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22098390/