Class variable assigned by expression
I have a class variable - a list - which values ββare generated dynamically by understanding, for example:
class A:
Field = [2**x for x in range(8)]
. . .
My question is, is this value calculated after the class is imported A
or every time I call A.Field
? How does Python deal with such declarations, are there any limitations or hidden obstacles?
source to share
The expression is evaluated once when the statement is executed class
(in Python, things like class
and def
are executable statements ).
When you do this, all instances A
or subclasses will have the same Field
.
... this is the value computed after importing class A ...
Note that there are no "imported" ones here. If you put a statement class
inside a module and import that module more than once, the statement will still only be executed once.
source to share