Periodic Maintenance
Periodic Maintenance

Reputation: 1777

Python instance attribute takes initial value from class attribute with the same name?

class bambino(object):
    counter = 7
    def __init__(self):
        print("bambino.counter is self.counter ?", bambino.counter is self.counter)
        self.counter += 1
        print("bambino.counter is self.counter ?", bambino.counter is self.counter)

bambi1 = bambino()
print ("bambi1.counter:", bambi1.counter)
print ("bambino.counter:", bambino.counter)

prints:

bambino.counter is self.counter ? True
bambino.counter is self.counter ? False
bambi1.counter: 8
bambino.counter: 7

I understand that by doing self.counter += 1 counter becomes an attribute of the instance not of the class.

But why did bambi1.counter take it's initial value from bambino.counter?

Upvotes: 1

Views: 108

Answers (1)

Pavel Anossov
Pavel Anossov

Reputation: 62908

If an attribute is not found in an object, it gets looked up higher in the hierarchy, first in its class, and then, if not found, in the superclasses.

self.counter += 1 is equivalent to self.counter = self.counter + 1. So to assign the bambi1.counter, Python first needs to get the value of bambi1.counter. Since the bambi1 does not initially have a counter, python doesn't find it and has to look it up in its class.

PS: Please capitalize your class names.

Upvotes: 5

Related Questions