Inheritance: Overriding private/public data attributes and methods in Python3


#1

Hi, I tried search up these questions online but still couldn’t understand it.

Can subclasses inherit private data fields and methods declared in the superclass? They said something about name mangling. When I run the code below, I get an error. AttributeError: ‘Child’ object has no attribute ‘_Child__x’. What does this mean?

class Parent:
    def __init__(self):
        self.__x = 10


class Child(Parent):
    def __init__(self):
        super().__init__()

    def get_x(self):
        return self.__x


c = Child()
print(c.get_x())

#2

if we look at pep8 (link):

__double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).

so then we get:

class Parent:
    def __init__(self):
        self.__x = 10


class Child(Parent):

    def get_x(self):
        return self._Parent__x


c = Child()
print(c.get_x())

we can get access to x, but it requires some tangling because of name mangling.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.