这篇“python中关于super()函数的问题怎么解决”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“python中关于super()函数的问题怎么解决”文章吧。
class Person:
def run(self):
print('studying')
class Person1:
def run(self):
print('working')
class Person2:
def run(self):
print('playing')
class Person3(Person,Person1,Person2):
def run(self):
super().run1()
p=Person3()
p.run()
执行结果:
AttributeError: ‘super’ object has no attribute ‘run1’
注意:
1、一个类继承多个类时,如果父类中没有提供该方法,类会通过__mro__属性一直向上搜索,如果直到object还没有搜索到该方法,那么将会引发AttributeError异常
class Person:
def run(self):
print('studying')
class Person1:
def run(self):
print('working')
class Person2:
def run(self):
print('playing')
class Person3(Person,Person1,Person2):
def run(self):
super(Person1,self).run()
p=Person3()
p.run()
输出结果为:playing;而不是working
注意:
1、super()函数的使用。
使用super()函数时,可以通过super(类名,self)来指定对哪个对象以哪个类为起点向上搜索父类中的方法。
例如:super(Person1,self).run():表示以Person1类为起点,向上搜索self(Person3的对象)的run方法。
Person1向上搜索到了<class ‘main.Person2’>,所以才会输出playing
2、print(Person3.mro)的继承顺序为:(<class ‘main.Person3’>, <class ‘main.Person’>, <class ‘main.Person1’>, <class ‘main.Person2’>, <class ‘object’>)
class A:
def who(self):
print('A', end='')
class B(A):
def who(self):
super(B, self).who()
print('B', end='')
class C(A):
def who(self):
super(C, self).who()
print('C', end='')
class D(B, C):
def who(self):
super(D, self).who()
print('D', end='')
item = D()
item.who()
print(D.__mro__)
输出结果:
ACBD
(<class ‘main.D’>, <class ‘main.B’>, <class ‘main.C’>, <class ‘main.A’>, <class ‘object’>)
以上就是关于“python中关于super()函数的问题怎么解决”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。