CoCalc Public Filespy-private-attributes.ipynbOpen with one click!
Author: Harald Schilly
Views : 130
License: Apache License 2.0
Compute Environment: Ubuntu 18.04 (Deprecated)

How and hy private attribtues in python classes?

Scenario 1

We have a parent/child inheritance, which uses the same variable names.

In [1]:
class Foo1(object): def __init__(self, x): self.x = x def get_x(self): return self.x
In [2]:
class Bar1(Foo1): def __init__(self, x): super().__init__(x) self.x = 2*x def parent_x(self): return super().get_x()
In [3]:
a1 = Foo1(123) a1.get_x()

Note, the get_x method comes from the parent class – while the value x from the child class.

In [4]:
b1 = Bar1(123) b1.get_x()

Here is the catch: there is only one x in play and therefore the child class overwrote the parent classes' x attribute.

In [5]:
In [ ]:
In [ ]:

Scenario 2

We use Python's name-mangling (two leading underscores are replaced by _[class name]_) to introduce two x attributes in total. Therefore, we avoid them being overwritten.

In [6]:
class Foo2(object): def __init__(self, x): self.__x = x def get_x(self): return self.__x
In [7]:
class Bar2(Foo2): def __init__(self, x): super().__init__(x) self.__x = 2*x def get_x(self): return self.__x def parent_x(self): return super().get_x()
In [8]:
a2 = Foo2(123) a2.get_x()
In [9]:
b2 = Bar2(123) b2.get_x()
In [10]:
In [ ]: