从Python中的派生类方法调用基类方法

时间:2013-04-02 05:49:07

标签: python inheritance base-class

我有一个A类,我从A类继承了一个B类。 我有两种方法methodX& ClassA中的methodY。此方法Y将在classA中调用methodX。 现在我在ClassB中有一个方法Z。

以下是该方案: -

class A(object):
 def methodX(self):
  ....
 def methodY(self):
  methodX()

class B(A)
 def methodZ(self):
  self.methodY() #says the global methodX is not defined 

我的问题是我必须调用methodY,它从methodZ调用methodX。这怎么可能?我应该全局定义methodX吗?还是有其他选择.. 提前谢谢!

3 个答案:

答案 0 :(得分:3)

methodY中,您应该致电self.methodX()

答案 1 :(得分:0)

由于在不使用该类的对象的情况下无法调用成员函数,因此抛出此错误。使用

self.methodX()

使用用于调用methodX()的对象

使用对象调用函数methodY()

答案 2 :(得分:0)

如前所述,使用self.methodX()似乎正在解决您的问题。 检查一下:

class A(object):
    def methodX(self):
        print "A.methodX"
    def methodY(self):
        print "A.methodY"
        self.methodX()

class B(A):
    def methodZ(self):
        print "B.methodZ"
        self.methodY()

b = B()
b.methodZ()

生成此输出:

$ python test.py
B.methodZ
A.methodY
A.methodX
$

我认为这就是你要找的......

相关问题