Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing field outside __init__

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.

like image 449
Håkon K. Olafsen Avatar asked Dec 19 '25 03:12

Håkon K. Olafsen


1 Answers

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.)

like image 78
Sven Marnach Avatar answered Dec 20 '25 15:12

Sven Marnach