码迷,mamicode.com
首页 > 编程语言 > 详细

Python3---常见函数---super()

时间:2020-01-03 10:41:17      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:版本   super   注意   ade   ESS   父类   问题   查找   xxx   

0X01;super()函数的作用?

  super() 函数是用于调用父类(超类)的一个方法。super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。

0X02;语法

  super(type[,object-or-type])

  type -- 类。

  object-or-type -- 类,一般是 self

  注意:Python3.x 和 Python2.x 的一个区别是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx :

0X03;举例:

 1 print("版本号3.x")
 2 ‘‘‘
 3 案例一:
 4 ‘‘‘
 5 class A:
 6     def add(self,x): #设定一个类方法
 7         y = x + 1
 8         print(y)
 9 #继承A类
10 class B(A):
11     def add(self,x):
12         print(x)
13        # super().add(x)
14 print(案例一)
15 a = A()
16 b = B()
17 a.add(2)
18 b.add(2)
19 super(B,b).add(2)
20 ‘‘‘
21 案例二:
22 ‘‘‘
23 print("案例二:")
24 class C:
25     def add(self,x): #设定一个类方法
26         y = x + 1
27         print(y)
28 #继承A类
29 class D(C):
30     def add(self,x):
31        super().add(x)
32 d = D()
33 d.add(2)
 1 C:\Users\aaron\Desktop\Pytoon-cade\venv\Scripts\python.exe C:/Users/aaron/Desktop/Pytoon-cade/urllib-Study.py
 2 版本号3.x
 3 案例一
 4 3
 5 2
 6 3
 7 案例二:
 8 3
 9 
10 Process finished with exit code 0

Python3---常见函数---super()

标签:版本   super   注意   ade   ESS   父类   问题   查找   xxx   

原文地址:https://www.cnblogs.com/aaron456-rgv/p/12143475.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!