您现在的位置是:网站首页> 编程资料编程资料
python中关于对super()函数疑问解惑_python_
                     2023-05-26
                342人已围观
                
                2023-05-26
                342人已围观
            
简介 python中关于对super()函数疑问解惑_python_
案例一:运行下面的代码结果是什么?
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向上搜索到了main .Person2’>,所以才会输出playing
2、print(Person3.mro)的继承顺序为:(
main .Person3’>,main.Person’>, main.Person1’>, main.Person2’>, ) 
案例三、更复杂些的继承,和上面的同理
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
(main .D’>,main.B’>, main.C’>, main.A’>, ) 
总结
到此这篇关于python中关于对super()函数疑问解惑的文章就介绍到这了,更多相关python super()函数解惑内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关内容
- 修复python-memcached在python3.8环境中报SyntaxWarning的问题(完美解决)_python_
- Python3中常见配置文件写法汇总_python_
- Python中requests库的基本概念与具体使用方法_python_
- 一文掌握python中的时间包_python_
- uwsgi启动django项目的实现步骤_python_
- Python+Pygame实战之英文版猜字游戏的实现_python_
- 使用pip下载时提示"You are using pip version 8.1.1, however version 22.1 is available."错误解决_python_
- Python中os模块的12种用法总结_python_
- Python PaddlePaddle机器学习之求解线性模型_python_
- python geemap的安装步骤及环境配置_python_
 
                                
                                                         
                                
                                                         
                                
                                                         
 
    