python - 如何从子类访问父类中的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”
解决方案
您需要在子类中初始化父实例,因为该__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)
推荐阅读
- asp.net - Azure 应用服务部署中心无法从 GitHub 存储库部署
- hibernate - 使用负载平衡扩展金融应用程序
- python - 在字典中设置值的pythonic方法
- gradle - 403 您无权执行促销 'snapshotToRelease'
- java - 使用抽象类构造堆
- google-cloud-platform - 通过部署管理器创建 GCP 项目
- java - Apache Camel:拆分和后续异常后如何在多个 Exchange 之间保留属性或标头?
- arrays - 在 vue Modal 中将数组作为道具传递
- xamarin.forms - 根本无法在 xamarin 表单中查看设计器选项
- python - 如何使用 python 在图中添加标记,如下所示?