python Python在父类中使用派生类的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2297843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python using derived class's method in parent class?
提问by
Can I force a parent class to call a derived class's version of a function?
我可以强制父类调用派生类的函数版本吗?
class Base(object):
attr1 = ''
attr2 = ''
def virtual(self):
pass # doesn't do anything in the parent class
def func(self):
print "%s, %s" % (self.attr1, self.attr2)
self.virtual()
and a class that derives from it
和一个派生自它的类
class Derived(Base):
attr1 = 'I am in class Derived'
attr2 = 'blah blah'
def virtual(self):
# do stuff...
# do stuff...
Clearing up vagueness:
清除模糊:
d = Derived()
d.func() # calls self.virtual() which is Base::virtual(),
# and I need it to be Derived::virtual()
采纳答案by Alex Martelli
If you instantiate a Derived
(say d = Derived()
), the .virtual
that's called by d.func()
isDerived.virtual
. If there is no instance of Derived
involved, then there's no suitable self
for Derived.virtual
and so of course it's impossible to call it.
如果您实例化 a Derived
(say d = Derived()
),则.virtual
调用的d.func()
是 isDerived.virtual
。如果没有Derived
涉及的实例,那么就没有合适self
的Derived.virtual
,所以当然不可能称之为。
回答by Jyaan
It isn't impossible -- there is a way around this actually, and you don't have to pass in the function or anything like that. I am working on a project myself where this exact problem came up. Here is the solution:
这并非不可能——实际上有一种方法可以解决这个问题,而且您不必传入函数或类似的东西。我自己正在做一个项目,这个项目出现了这个确切的问题。这是解决方案:
class Base(): # no need to explicitly derive object for it to work
attr1 = 'I am in class Base'
attr2 = 'halb halb'
def virtual(self):
print "Base's Method"
def func(self):
print "%s, %s" % (self.attr1, self.attr2)
self.virtual()
class Derived(Base):
attr1 = 'I am in class Derived'
attr2 = 'blah blah'
def __init__(self):
# only way I've found so far is to edit the dict like this
Base.__dict__['_Base_virtual'] = self.virtual
def virtual(self):
print "Derived's Method"
if __name__ == '__main__':
d = Derived()
d.func()