【问题标题】:Initializing a static field in a Python class在 Python 类中初始化静态字段
【发布时间】:2026-02-06 21:20:03
【问题描述】:

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

class Test:

    def _init_foo(): return 3

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

但是,口译员在抱怨

NameError: name '_init_foo' is not defined

我该如何解决这个问题?

【问题讨论】:

标签: python class static


【解决方案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}

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】: