Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 273
License: APACHE
Kernel: Python 3 (system-wide)

How/Why private attribtues in python classes?

Scenario 1

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

class Foo1(object): def __init__(self, x): self.x = x def get_x(self): return self.x
class Bar1(Foo1): def __init__(self, x): super().__init__(x) self.x = 2*x def parent_x(self): return super().get_x()
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.

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.

b1.parent_x()
246

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.

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