I have a class variable - a list - which values generated dynamically by comprehension, for example:
class A:
Field = [2**x for x in range(8)]
. . .
My question: is this value calculated once the class A was imported or every time I call the A.Field? How Python treats such declarations, is there some limitation or hidden hurdles?
The expression is evaluated once, when the class statement is being executed (in Python, things like class and def are executable statements).
When you do this, all instance of A or subclasses will share the same Field.
...is this value calculated once the class A was imported...
Note that there is no "imported" here. If you place the class statement inside a module, and import that module more than once, the statement will still only get executed once.
Here is an example showing that it is evaluated only once:
>>> l=range(2)
>>> l
[0, 1]
>>> class A:
... Field = l.pop()
...
>>> A.Field
1
>>> A.Field
1
>>> l
[0]
the .pop() is executed only once.
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