Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python static fields of own type

Tags:

python

I notice python won't let you add an instance of a class to itself as a static member at class definition.

>>> class Foo:
...     A = Foo()
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in Foo
NameError: name 'Foo' is not defined

However either of the following work:

>>> class Foo:
...     pass
... 
>>> class Foo:
...     A = Foo()
... 
>>> Foo.A
<__main__.Foo instance at 0x100854440>

or

>>> class Foo:
...     pass
... 
>>> Foo.A = Foo()
>>> 
>>> Foo.A
<__main__.Foo instance at 0x105843440>

I can't find any enlightening code examples or explanations. Why does python treat the first case differently? Where is A going in each of the two subsequent cases?

like image 460
Paul Orland Avatar asked Aug 14 '26 16:08

Paul Orland


1 Answers

Your first example doesn't work because you haven't created the class Foo yet. You're in the process of doing so (hence the NameError)

Your second example works because you have a class called Foo(). You override it, but you still keep a copy of it. Take a look at this:

>>> class Foo:
...     def __init__(self):
...             print 'hi'
... 
>>> class Foo:
...     A = Foo()
... 
hi
>>> Foo.A
<__main__.Foo instance at 0x101019950>
>>> Foo.A.__init__
<bound method Foo.__init__ of <__main__.Foo instance at 0x101019950>>

A is an attribute that has the value of a class you overrode.

As for your third example, you're simply making an attribute of a class that is an instance of the class.

like image 63
TerryA Avatar answered Aug 16 '26 07:08

TerryA



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!