super() 找MRO順序的下一個
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
# class Base1:
# def chi(self):
# print("我是可憐的Base1")
#
# class Base2:
# def chi(self):
# print("我是可憐的Base2")
#
# class Base3:
# def chi(self):
# print("我是可憐的Base3")
#
# class Bar(Base1, Base2, Base3):
# def chi(self):
# print("我是Bar裏面的吃1")
# # super(類名, self) 從某個類開始找下一個MRO
# super(Base2, self).chi() # 此時調用的super. 在Bar調用 -> super表示找MRO裏的下一個
# # super().chi() # super(Bar, self).chi()
# print("我是Bar裏面的吃2")
#
# b = Bar() # Bar, Base1, Base2, Base3, object
# b.chi()
# print(Bar.__mro__)
# class Base1:
# def chi(self):
# super().chi() # super找的是MRO的下一個.
# print("我是可憐的Base1")
#
# class Base2:
# def chi(self):
# super().chi()
# print("我是可憐的Base2")
#
# class Base3:
# def chi(self):
# print("我是可憐的Base3")
#
# class Bar(Base1, Base2, Base3):
# def chi(self):
# print("我是Bar裏面的吃1")
# # super(類名, self) 從某個類開始找下一個MRO
# super(Bar, self).chi() # 此時調用的super. 在Bar調用 -> super表示找MRO裏的下一個
# # super().chi() # super(Bar, self).chi()
# print("我是Bar裏面的吃2")
#
# b = Bar() # 報錯 Base1 object
# b.chi() # 報錯
# # 坑
# MRO + super ⾯試題
class
Init(
object
):
def
__init__(
self
, v):
# 2
print
(
"init"
)
self
.val
=
v
class
Add2(Init):
def
__init__(
self
, val):
# 2
print
(
"Add2"
)
super
(Add2,
self
).__init__(val)
# Mult
print
(
self
.val)
self
.val
+
=
2
class
Mult(Init):
def
__init__(
self
, val):
print
(
"Mult"
)
super
(Mult,
self
).__init__(val)
# Haha
self
.val
*
=
5
class
HaHa(Init):
def
__init__(
self
, val):
print
(
"哈哈"
)
super
(HaHa,
self
).__init__(val)
# Init
self
.val
/
=
5
class
Pro(Add2,Mult,HaHa):
#
pass
class
Incr(Pro):
# incr->pro->add2->Mult->HaHa->init
def
__init__(
self
, val):
# 5
super
(Incr,
self
).__init__(val)
# Add2
self
.val
+
=
1
# Add2
# Mult
# 哈哈
# init
# 5.0
# 8.0
# Add2
# init
# 2
# 4
|