Python oop polymorphism

I can not understand why this code:

class A(object):
    def __init__(self):
        self.__value = 1
    def get_value(self):
        return self.__value

class B(A):
    def __init__(self):
        A.__init__( self )
        self.__value = 2

b = B()

print b.get_value()

gives 1, but not 2. Thanks for your help.

+3
source share
2 answers

Your problem is that double underscores are special in python and create some privacy modicum (not mandatory, but it manages names that are what affects you here). You must recreate this without a variable variable with double underscores. In addition, you should use superinstead of a direct call A.__init__:

>>> class A(object):
...     def __init__(self):
...             self.value = 1
...     def get_value(self):
...             return self.value
... 
>>> class B(A):
...     def __init__(self):
...             super(B, self).__init__()
...             self.value = 2
... 
>>> b = B()
>>> b.get_value()
2

For more details, if you do not want to read the reference documentation:

"special" , , __. : A.get_value() _A__value, self.__value B - _B__value, , A.get_value() .

, - :

>>> class A(object):
...     def get_value(self):
...             return self._B__value
... 
>>> class B(A):
...     def __init__(self):
...             self.__value = 2
... 
>>> b = B()
>>> b.get_value()
2
+7

self.__value = 1 'private', .

.

. self._value = 1

, , Python __dict__:

>>> class A(object):
...     def __init__(self):
...         self.__value = 1
...     def get_value(self):
...         return self.__value
...
>>> A().__dict__
{'_A__value': 1}

__value .

+3
source

All Articles