首页 > 解决方案 > 如何从子类访问父类中的show方法?

问题描述

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()

文件“main.py”,第 12 行,在 show
super().show()
文件“main.py”,第 6 行,在 show
print("Parent:",self.__num)
AttributeError: 'Child' object has no属性“_Parent__num”

标签: pythonoop

解决方案


您需要在子类中初始化父实例,因为该__num属性仅在Parent's 初始化期间设置,而不是在Child's.

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

推荐阅读