如何检查Python中是否存在静态变量?

时间:2014-02-28 14:51:05

标签: python static-members

这是一个相关的问题: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中是否存在静态变量?

1 个答案:

答案 0 :(得分:6)

您使用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'

(注意,这两种方法都不是线程安全的)

相关问题