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?

+3


source to share


2 answers


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.

+7


source


Here's an example to show that it is only evaluated once:

>>> l=range(2)
>>> l
[0, 1]
>>> class A:
...   Field = l.pop()
...
>>> A.Field
1
>>> A.Field
1
>>> l
[0]

      



.pop()

is executed only once.

+3


source







All Articles