在类定义中,super()等价于super(Child, self)。实际上解释器使用的是__class__变量,每个函数中都能访问这个变量,它指向这个函数对应的类。注意,这个特殊语法只能在Python3中使用,不能在Python2中使用。这个新的功能是2007年引入到Python 3.0版本中的,详见PEP-3135提案。3.__init__/__new__以及实
class A: def run(self): print('AAA')class B: def run(self): print('BBB')class C: def run(self): print('CCC')class D(A, B, C): def run(self): # 调用 C 中 run super(B, self).run()d = D()d.run()此时输出的结果是 CCC,该结果输出表示了使用 super 函数之后,可以使用 s...
Thisisfrom Parent#实例化子类Child的fun函数时,首先会打印上条的语句,再次调用父类的fun函数方法 #python 3.6版本中super().父类的方法 #Python 2.7版本中super(子类,self).父类方法,父类类名称后Fish(object) import random as r class Fish: def __init__(self): self.x = r.randint(0,100) self.y...
class super(object) | super() -> same as super(__class__, <first argument>) | super(type) -> unbound super object | super(type, obj) -> bound super object; requires isinstance(obj, type) | super(type, type2) -> bound super object; requires issubclass(type2, type) | Typical use...
以下展示了使用 super 函数的实例: 实例 #!/usr/bin/python # -*- coding: UTF-8 -*- class FooParent(object): def __init__(self): self.parent = 'I\'m the parent.' print ('Parent') def bar(self,message): print ("%s from Parent" % message) class FooChild(FooParent): def __...
1.super被引入的初衷 super()通常是被说成super函数,其实它是一个内置的类,是在Python2.2中新增加的,super()实例化一个super对象,这个super对象充当一个访问代理的角色,它帮助子类的对象访问父类,祖父类以及所有祖先类中被方法(尤其是访问那些被子类重写的方法)。
首先定义一个菱形继承 ABCD,此时最值得注意的是 B 类的 super 调用,此时 B 的基类是 A,但是 B 的 super 调用的却是类 C 的初始化函数,这是由于 MRO 的搜索规则所决定的。 1classA:2def__init__(self, name):3print("A init.")4self.name =name56classB(A):7def__init__(self, age):8print...
class A: def spam(self): print('A.spam') class B(A): def spam(self): print('B.spam') super().spam() # Call parent spam() 1. 2. 3. 4. 5. 6. 7. super() 函数的一个常见用法是在 __init__() 方法中确保父类被正确的初始化了: ...
(object):defm(self):''' m in A'''return"A"classB(A):defm(self):''' m in B'''return"B"+Super(B,self).m()classC(A):defm(self):''' m in C '''return"C"+Super(C,self).m()classD(C):defm(self):''' m in D'''return"D"+Super(B,self).m()print(D().m())...