在Python 3.x中,super()可以不带参数调用:
class A(object):
def x(self):
print("Hey now")
class B(A):
def x(self):
super().x()
Run Code Online (Sandbox Code Playgroud)
>>> B().x()
Hey now
Run Code Online (Sandbox Code Playgroud)
为了使这项工作,一些编译时间魔法进行,其中的一个后果是,下面的代码(重新绑定super到super_)失败:
super_ = super
class A(object):
def x(self):
print("No flipping")
class B(A):
def x(self):
super_().x()
Run Code Online (Sandbox Code Playgroud)
>>> B().x()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in x
RuntimeError: super(): __class__ cell not found
Run Code Online (Sandbox Code Playgroud)
super()如果没有编译器的帮助,为什么无法在运行时解析超类?是否存在这种行为或其潜在原因可能会让一个不知情的程序员陷入困境的实际情况?
...并且,作为一个附带问题:在Python中是否有任何其他函数,方法等示例可以通过将它们重新绑定到不同的名称来打破?
我正在玩python中的多重继承,我遇到了一个我无法理解它是如何发生的情况.
这是继承布局:
A F
/ \ |
B C |
\ | /
\ | /
D
Run Code Online (Sandbox Code Playgroud)
每个人都熟悉的ABCD钻石.加上额外的"F"级别,我把它扔进去玩.
这是代码:
class A(object):
def foo(self, call_from):
print "foo from A, call from %s" % call_from
super(A, self).foo("A")
class B(A):
def foo(self, call_from):
print "foo from B, call from %s" % call_from
super(B, self).foo("B")
class C(A):
def foo(self, call_from):
print "foo from C, call from %s" % call_from
super(C, self).foo("C")
class F(object):
def foo(self, call_from):
print "foo from F, call from %s" % …Run Code Online (Sandbox Code Playgroud) 我尝试从内部访问父类的类方法,__init_subclass__但似乎不起作用.假设以下示例代码:
class Foo:
def __init_subclass__(cls):
print('init', cls, cls.__mro__)
super(cls).foo()
@classmethod
def foo(cls):
print('foo')
class Bar(Foo):
pass
Run Code Online (Sandbox Code Playgroud)
这会产生以下异常:
AttributeError: 'super' object has no attribute 'foo'
Run Code Online (Sandbox Code Playgroud)
cls.__mro__然而,这表明它Foo是其中的一部分:(<class '__main__.Bar'>, <class '__main__.Foo'>, <class 'object'>).
所以我不明白为什么super(cls).foo()不派遣Foo.foo.有人可以解释一下吗?