在Python类中初始化静态字段

时间:2018-10-30 09:45:24

标签: python class static

我想在声明时初始化一个静态字段。

class Test:

    def _init_foo(): return 3

    foo = { _init_foo() for i in range(10)}

但是,口译员在抱怨

NameError: name '_init_foo' is not defined

我该如何解决?

2 个答案:

答案 0 :(得分:1)

失败的原因是explained here

您可以通过class decorator定义foo来解决此问题。之所以可行,是因为在调用add_foo时,已经定义了该类,并且可以通过_init_foo来访问cls._init_foo

def add_foo(cls):
    cls.foo = { cls._init_foo() for i in range(10) }
    return cls

@add_foo
class Test:

    def _init_foo(): return 3


print(Test.foo)
# {3}

答案 1 :(得分:1)

在找到类装饰器选项之前,我正在类声明之后初始化字段。我不知道我不喜欢哪一个... :)我错过了Java中的静态初始化块。

class Box:

    def __init__(self, x):
        self.x = x
        Box.count += 1  # static field usage

    @staticmethod
    def instance_count():
        return Box.count  # static field usage

Box.count = 0  # static field initialisation

b1 = Box(10)
b2 = Box(20)
print(Box.count)  # 2