文字版是这一篇:
https://blog.csdn.net/wo198711203217/article/details/84097274?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param
演示二的代码:
演示二的输出
使用super 函数调用
这段代码要和演示二重点对比分析~采用super 和不采用,有何异同!
具体super 的运行机制,本文就不赘述了,想了解的可以去看原文~
https://blog.csdn.net/wo198711203217/article/details/84097274?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param
python super函数
在类的继承中,
o如果重定义某个方法,该方法会覆盖父类的同名方法,
o但有时,我们希望能同时实现父类的功能,
这时,我们就需要调用父类的方法了。
调用父类同名方法有两种方式:
o 1、调用未绑定的父类方法
案例一
class Base(object):
o def greet(self):
print(‘hi,I am Base’)
class A(Base):
o def greet(self):
Base.greet(self)
#通过父类Base直接调用greet方法,并把self作为参数
print(‘hi,I am A’)
a=A()
a.greet()
运行结果:
ohi,I am Base
ohi,I am A
oProcess finished with exit code 0
这种方式简单用还可以,如果在多重继承中就会有问题。
本文重点!!!
演示二:
class Base(object):
o def init(self):
print(“enter Base”)
print(“leave Base”)
class A(Base):
o def init(self):
print(“enter A”)
Base.init(self)
#调用父类的构造函数进行初始化
print(“leave A”)
class B(Base):
o def init(self):
print(“enter B”)
Base.init(self)
#调用父类的构造函数进行初始化
print(“leave B”)
class C(A,B):
o def init(self):
print(“enter C”)
A.init(self)
#调用父类A的构造函数进行初始化
分别初始化,和后面的super 调用不一样,留心差别
B.init(self)
#调用父类B的构造函数进行初始化
print(“leave C”)
c=C()
运行结果:
oenter C
oenter A
oenter Base
oleave Base
oleave A
oenter B
oenter Base
oleave Base
oleave B
oleave C
分析
o基类Base的构造函数被调用了两次,这是有问题的
o正常的应该是:
A的构造函数调用一次,
B的构造函数调用一次,
基类Base的构造函数调用一次。
o2、使用super函数来调用
演示
class Animal(object):
o def init(self, name):
self.name = name
o def greet(self):
print(‘Hello, I am %s.’ % self.name)
class Dog(Animal):
o def greet(self):
super(Dog, self).greet()
#调用父类Animal的greet方法
为了能同时实现父类的功能,我们又调用了父类的方法
print(‘WangWang…’)
在 Dog 类重定义了 greet 方法
d=Dog(“xiaohuang”)
d.greet()
运行结果:
oHello, I am xiaohuang.
oWangWang…
super 的一个最常见用法可以说是在子类中调用父类的初始化方法了。
演示:
oclass Base(object):
def init(self, a, b):
self.a = a
self.b = b
oclass A(Base):
def init(self, a, b, c):
super(A, self).init(a, b)
o# Python3 可使用 super().init(a, b)
self.c = c
oa=A(100,200,300)
oprint(“a=%d, b=%d, c=%d” % (a.a,a.b,a.c))
运行结果:
oa=100, b=200, c=300
深入super()
super 其实和父类没有实质性的关联
参考未绑定父类的案例
oclass Base(object):
def init(self):
print(“enter Base”)
print(“leave Base”)
oclass A(Base):
def init(self):
print(“enter A”)
super(A,self).init()
print(“leave A”)
oclass B(Base):
def init(self):
print(“enter B”)
super(B,self).init()
print(“leave B”)
oclass C(A,B):
def init(self):
print(“enter C”)
super(C,self).init()
o和前者的差别在这里
print(“leave C”)
oc=C()
o输出
enter C
enter A
enter B
enter Base
leave Base
leave B
leave A
leave C
super 是怎么运作的。本文就不解释了,可以去看原文