Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class variable assigned by expression

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?

like image 933
rook Avatar asked Jul 28 '26 22:07

rook


2 Answers

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.

like image 169
NPE Avatar answered Jul 30 '26 13:07

NPE


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.

like image 23
fredtantini Avatar answered Jul 30 '26 13:07

fredtantini



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!