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?

nstrong
  • 209
  • 2
  • 8
  • 1
    This discussion may be helpful: https://stackoverflow.com/questions/1641219/does-python-have-private-variables-in-classes – WillardSolutions Nov 07 '17 at 15:55
  • If you read up on the Python documentation for [Private Variables](https://docs.python.org/3.6/tutorial/classes.html#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**." – glibdud Nov 07 '17 at 15:58

1 Answers1

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
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895