Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a static field in a Python class

I want to initialize a static field on declaration.

class Test:

    def _init_foo(): return 3

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

However, the interpreter is complaining

NameError: name '_init_foo' is not defined

How do I fix this?

like image 622
Jsevillamol Avatar asked Feb 25 '26 06:02

Jsevillamol


1 Answers

Why this fails is explained here.

You could work around the problem by defining foo via a class decorator. This works because by the time add_foo is called, the class has been defined and _init_foo in then accessible as 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}
like image 122
unutbu Avatar answered Feb 26 '26 19:02

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!