我有一个关于python的super()和多重继承的语法问题。假设我有A和B类,两者都有hello()方法。我有一个C类继承自A和B的顺序。python超级问题
如何从C显式调用B的hello()方法?似乎很简单,但我似乎无法找到它的语法。
我有一个关于python的super()和多重继承的语法问题。假设我有A和B类,两者都有hello()方法。我有一个C类继承自A和B的顺序。python超级问题
如何从C显式调用B的hello()方法?似乎很简单,但我似乎无法找到它的语法。
从C
hello
方法显式调用B
的:
B.hello(self,...)
>>> class A(object):
def hello(self):
print "hello from A"
>>> class B(object):
def hello(self):
print "hello from B"
>>> class C(A, B):
def hello(self):
print "hello from C"
>>> c = C()
>>> B.hello(c)
hello from B
>>> # alternately if you want to call it from the class method itself..
>>> class C(A, B):
def hello(self):
B.hello(self) # actually calling B
>>> c = C()
>>> c.hello()
hello from B
你可能要考虑使用超() - 而不是硬编码B.hello() - 作为解释在Python's super() considered super。在这种方法中,C.hello()使用super()并自动调用A.hello(),然后使用super()并自动调用B.hello(),而不需要对类名进行硬编码。
否则,B.hello()确实是做你想做的事的正常方法。
+1用于指向Hettinger super()文章的指针。 – bgporter