 CoCalc Public Filespy-private-attributes.ipynb
Author: Harald Schilly
Views : 130
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 :
class Foo1(object):
def __init__(self, x):
self.x = x
def get_x(self):
return self.x

In :
class Bar1(Foo1):
def __init__(self, x):
super().__init__(x)
self.x = 2*x
def parent_x(self):
return super().get_x()

In :
a1 = Foo1(123)
a1.get_x()

123

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

In :
b1 = Bar1(123)
b1.get_x()

246

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

In :
b1.parent_x()

246
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 :
class Foo2(object):
def __init__(self, x):
self.__x = x
def get_x(self):
return self.__x

In :
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 :
a2 = Foo2(123)
a2.get_x()

123
In :
b2 = Bar2(123)
b2.get_x()

246
In :
b2.parent_x()

123
In [ ]: