1

Here is my code:

class Dog:
    def __init__(self,name,age):
        self.n = name
        self.__a = age
lucy=Dog("lucy",2)
print(lucy.__a)

jack=Dog("jack",3)
jack.__a=10
print(jack.__a)

When I run it, print(lucy.__a) gives me an error, which is understandable, because __a is a private instance variable. What confuses me a bit is that, print(jack.__a) works perfectly fine. I think it's because we have the jack.__a=10 before it. Could anyone explain to me exactly what is going on?

2
  • 1
    This discussion may be helpful: stackoverflow.com/questions/1641219/… Commented Nov 7, 2017 at 15:55
  • If you read up on the Python documentation for Private Variables, you'll see this line: "This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class." Commented Nov 7, 2017 at 15:58

1 Answer 1

3

Examining the results of dir(jack) shows what is going on:

['_Dog__a', '__a', ...]

Assigning the __a attribute from within the class invokes name mangling; the value is stored against _Dog__a. But assigning it from outside does not invoke that, so a separate value is stored on the instance as __a. So you can do:

>>> jack._Dog__a
3
>>> jack.__a
10
Sign up to request clarification or add additional context in comments.

Comments

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.