【发布时间】:2022-01-10 14:06:41
【问题描述】:
假设我们有不同类型的人,钢琴家、程序员和多才多艺的人。 那么,我该如何继承呢?目前此代码给出错误 Multitalented has no attribute canplaypiano。
class Pianist:
def __init__(self):
self.canplaypiano=True
class Programer:
def __init__(self):
self.canprogram=True
class Multitalented(Pianist,Programer):
def __init__(self):
self.canswim=True
super(Pianist,self).__init__()
super(Programer,self).__init__()
Raju=Multitalented()
print(Raju.canswim)
print(Raju.canprogram)
print(Raju.canplaypiano)
另外,请提及一些关于 python 继承/super() 的写得很好的文章,我找不到解释清楚的完美文章。谢谢。
【问题讨论】:
-
使用
Pianist.__init__(self)或super().__init__()。不要混合对基类的显式引用和超级引用。请注意,继承层次结构中的 all 或 no 类应使用super。 -
您从根本上误解了
super的参数是如何工作的。阅读以下内容:rhettinger.wordpress.com/2011/05/26/super-considered-super 还有来自 PyCon 的相应视频演示:youtube.com/watch?v=EiOglTERPEo
标签: python inheritance multiple-inheritance