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?
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With