2011-06-24 75 views
0

我有一个关于python的super()和多重继承的语法问题。假设我有A和B类,两者都有hello()方法。我有一个C类继承自A和B的顺序。python超级问题

如何从C显式调用B的hello()方法?似乎很简单,但我似乎无法找到它的语法。

回答

5

Chello方法显式调用B的:

B.hello(self,...) 
4
>>> 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 
3

你可能要考虑使用超() - 而不是硬编码B.hello() - 作为解释在Python's super() considered super。在这种方法中,C.hello()使用super()并自动调用A.hello(),然后使用super()并自动调用B.hello(),而不需要对类名进行硬编码。

否则,B.hello()确实是做你想做的事的正常方法。

+2

+1用于指向Hettinger super()文章的指针。 – bgporter

-1

请记住,Python从右向左调用超类方法。

+0

它呢?不,它不。 MRO从左到右,无论在哪里都是有意义的。 – SingleNegationElimination