Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用名称相同且相互依赖的方法处理python继承?_Python - Fatal编程技术网

如何使用名称相同且相互依赖的方法处理python继承?

如何使用名称相同且相互依赖的方法处理python继承?,python,Python,我努力维持一个班级。我希望的基本程序结构如下所示 class FooFather(): def __init__(self): self.meta=0 def add(self): self.meta+=1 def act(self): self.add() class FooChild(FooFather): def __init__(self): FooFather.__init__(self)

我努力维持一个班级。我希望的基本程序结构如下所示

class FooFather():
    def __init__(self):
        self.meta=0
    def add(self):
        self.meta+=1
    def act(self):
        self.add()
class FooChild(FooFather):
    def __init__(self):
        FooFather.__init__(self)
    def add(self):
        self.meta+=2
    def act(self):
        FooFather.act(self)
结果如下所示

foo=FooChild()
foo.act()
print(foo.meta)
=>2     //not 1 I want to have

我理解这个机制。子类覆盖父类的方法(add和act)。如何在覆盖方法的同时保持原始方法之间的关系?

self
指当前实例。因此,当
foodaver.act()
调用
self.add()
时,它是指当前实例的
add
方法,该实例是
FooChild()
实例。因此调用
FooChild.add(self)


如果你想调用
foodafter.act()
调用
foodafter.add()
,你需要让
foodafter.act()
明确地这样做:即
foodafter.add(self)

根据你的问题不确定你真正想要什么,但我猜是这样的,其中,
act
调用超类“
add
(使用python 2.7语法):


您可以使用伪私家车,请参见


什么是
foo.shot()
?如果只调用超类实现,为什么要重写
act
?为什么不重写它,让超类1自动调用呢。这是一个错误的选择@PadRaiccunningham那么您试图重写一个函数,而不重写超类,同时保持相同的名称?@aensm完全正确!是不是太野心勃勃了。这是一个解决办法。当父亲班很大的时候,就不是那么完美了。如果我想保持相同的API,我必须让我的手“脏”,也就是说,我几乎需要重写这些方法。我想象的是,我调用父的方法,并且将调用它自己的方法,而不是当前实例。感谢我拙劣的解释。。。
class FooFather(object):
    def __init__(self):
        self.meta=0
    def add(self):
        self.meta+=1
    def act(self):
        self.add()
class FooChild(FooFather):
    def __init__(self):
        super(FooChild, self).__init__()
    def add(self):
        self.meta+=2
    def act(self):
        super(FooChild, self).add()
class FooFather:
    def __init__(self):
        self.meta = 0

    def __add(self):
        print self.meta, '-->',
        self.meta += 1
        print self.meta

    def act(self):
        self.__add()

class FooChild(FooFather):
    def __add(self):
        print self.meta, '==>',
        self.meta += 2
        print self.meta

    def act2(self):
        FooFather.act(self)

    def act3(self):
        self.__add()



>>> c = FooChild()
>>> c.act()
0 --> 1
>>> c.act2()
1 --> 2
>>> c.act3()
2 ==> 4