0

could somebody explain me why this prints out 2 and not 3? i would thing that __var class variable would be overrided in Class Bottom with the value 3 and when the get method (inherited from class Middle) gets called, it would print out the overridden __var equals 3:

class Top:
    __var = 1
    
    def get(self):
        return self.__var

class Middle(Top):
    __var = 2

    def get(self):
        return self.__var

class Bottom(Middle):
    __var = 3


obj1 = Top()
obj2 = Middle()
obj3 = Bottom()

print(obj3.get())
    
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
NeXuS
  • 1
  • 4
  • 4
    The double underscore causes the name to be [mangled](https://stackoverflow.com/q/1301346/3282436). As such, anything beginning with a double underscore will never change through inheritance. This example works as expected if you use single underscores. – 0x5453 Jan 25 '22 at 20:12
  • 3
    By the way this is the *point* of using double underscores. – mkrieger1 Jan 25 '22 at 20:17
  • I'm sorry, python's class variables and method resemble something that I'm used to call "static". Basically what you're telling me is that in the subclasses, everything marked with double underscore (and not istance objects) are not inherited but created ex-novo, right? Just like private attributes in other languages. Therefore the last __var is a totally new class variable which is never used, did i get it right? – NeXuS Jan 26 '22 at 07:00

0 Answers0