简体   繁体   English

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

[英]How to deal with python inheritance with methods that have same names and depend each other?

I try to maintain a class. 我试图维持一堂课。 The basic program struct I hoped shows below. 我希望下面显示基本程序结构。

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)

The result shows below. 结果如下所示。

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

I understand the mechanism. 我了解机制。 The child class overwrites the methods of father (both add and act). 子类覆盖父类的方法(添加和执行)。 How can I overwrite a method meanwhile I can keep the relation between original methods? 在保留原始方法之间的关系的同时,如何覆盖方法?

self refers to the current instance. self是指当前实例。 So when FooFather.act() calls self.add() it is referring to the add method of the current instance, which is a FooChild() instance. 因此,当FooFather.act()调用self.add()它引用的是当前实例的add方法,即FooChild()实例。 Therefore FooChild.add(self) is called. 因此,将FooChild.add(self)

If you want FooFather.act() to call FooFather.add() instead, you need to have FooFather.act() do so explicitly: ie, FooFather.add(self) 如果要让FooFather.act()调用FooFather.add() ,则需要让FooFather.act()明确地执行此操作:即, FooFather.add(self)

Not sure what you want really based on your question, but I'm guessing something like this, where act calls the superclass' add (using python 2.7 syntax): 不确定基于您的问题真正想要的是什么,但是我猜测是这样的,其中act调用超类的add (使用python 2.7语法):

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()

You can use pseudo privates, see https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references 您可以使用伪私有,请参阅https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM