我试着维持一个类。我希望的基本程序结构如下所示。
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)。如何在重写方法的同时保持原方法之间的关系?
发布于 2014-06-24 03:27:45
self是指当前实例。因此,当FooFather.act()调用self.add()时,它引用的是当前实例的add方法,这是一个FooChild()实例。因此,FooChild.add(self)被调用。
如果您希望FooFather.act()调用FooFather.add(),则需要让FooFather.act()显式执行此操作:即FooFather.add(self)
发布于 2014-06-24 03:47:32
根据你的问题,我不确定你想要什么,但我猜是这样的,其中act调用超类‘add (使用Python2.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()发布于 2014-06-24 04:14:25
您可以使用伪私有,请参阅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 ==> 4https://stackoverflow.com/questions/24373628
复制相似问题