I need a bit of help to understand how python initialising works. I have a class (Bar) with another class (Foo) as a field/variable. When I try to initialise this variable directly in Bar (not in the class __init__) all instances of Bar will point to the same Foo. But if I have an __init__ method, as in Bar2, each Bar2 instance will have a unique Foo instance. What is happening here?
class Foo():
number = 0
class Bar():
foo = Foo()
class Bar2():
foo = None
def __init__(self):
self.foo = Foo()
first = Bar()
second = Bar()
print "Bar"
print first
print second
print first.foo
print second.foo
first = Bar2()
second = Bar2()
print "\nBar2"
print first
print second
print first.foo
print second.foo
The output will for example be:
Bar
<\__main__.Bar instance at 0x025B2AF8>
<\__main__.Bar instance at 0x025B2B20>
<\__main__.Foo instance at 0x004A3AA8>
<\__main__.Foo instance at 0x004A3AA8>
Bar2
<\__main__.Bar2 instance at 0x025B2B48>
<\__main__.Bar2 instance at 0x025B2AF8>
<\__main__.Foo instance at 0x025B2B70>
<\__main__.Foo instance at 0x025B2B98>
Using Bar both instances will refer to the same Foo instance. Why?
Edit: Corrected the error with printing first.foo twice for Bar. The resulting behaviour is still as seen in the output.
Bar.foo is a class variable. It is initialised once when the class is created.
(Note that your code als print first.foo twice, so no wonder the output is the same.)
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