简体   繁体   中英

How to access show method in parent class from child class?

class Parent:
    def __init__(self):
        self.__num = 100

    def show(self):
        print("Parent:",self.__num)

class Child(Parent):  
    def __init__(self):
        self.__var = 10
    def show(self):
        super().show()
        print("Child:",self.__var)   

obj1 = Child()
obj1.show()

File "main.py", line 12, in show
super().show()
File "main.py", line 6, in show
print("Parent:",self.__num)
AttributeError: 'Child' object has no attribute '_Parent__num'

You need to initialize the parent instance in your child class, because the __num attribute is only set during Parent 's initialization, and not during the Child 's.

class Child(Parent):  
    def __init__(self):
        super().__init__()
        self.__var = 10
    def show(self):
        super().show()
        print("Child:",self.__var)   
class Parent:
    def __init__(self):
        self.__num = 100

    def show(self):
        print("Parent:",self.__num)

class Child(Parent):  
    def __init__(self):
        super().__init__()  # Solution
        self.__var = 10

    def show(self):
        super().show()
        print("Child:",self.__var)   

obj1 = Child()
obj1.show()

To avoid overridding try this.

class Parent:
  def __init__(self):
    self.__num = 100

  def show(self):
     print("Parent:",self.__num)

class Child(Parent):  
  def __init__(self):
     Parent.__init__(self)
     self.__var=10
  def show1(self):
    print("Child:",self.__var)   

obj1 = Child()
obj1.show()

Change your Child. init to something like:

def __init__(self):
    self.__var = 10
    super().__init__()

as the other answers already said, you need to add super().__init__() to the __init__ of your child class.

but also note that there is something called name mangling at work here. read eg the 3. Double Leading Underscore: __var on this page .

the short version is: if you wanted to use the attribute self.__num also in the child class you should rename it to self._num (one underscore only).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM