代码之家  ›  专栏  ›  技术社区  ›  Jsevillamol

初始化Python类中的静态字段

  •  0
  • Jsevillamol  · 技术社区  · 6 年前

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

    class Test:
    
        def _init_foo(): return 3
    
        foo = { _init_foo() for i in range(10)}
    

    NameError: name '_init_foo' is not defined
    

    我该怎么解决这个问题?

    1 回复  |  直到 6 年前
        1
  •  1
  •   unutbu    6 年前

    失败的原因是 explained here .

    你可以通过定义 foo 通过 class decorator 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
  •  1
  •   Ferran Maylinch    5 年前

    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