1
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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Might be worth mentioning that the behavior is different for mutable objects when they are just modified and not reassigned.
It's not the mutability per se, it's that some types have += overloaded to mutate the object in-place instead.
Ah I didn't even think of the += case but more generic cases like foo = {} in the class and then self.foo[..] = ..
This isn't a problem if you already understand that mutating an object is fundamentally different from replacing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.