我可以强制父类调用派生类的函数版本吗?
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()
和一个派生自它的类
class Derived(Base):
attr1 = 'I am in class Derived'
attr2 = 'blah blah'
def virtual(self):
# do stuff...
# do stuff...
清除模糊:
d = Derived()
d.func() # calls self.virtual() which is Base::virtual(),
# and I need it to be Derived::virtual()
答案 0 :(得分:9)
如果您实例化Derived
(说d = Derived()
),则.virtual
调用的d.func()
Derived.virtual
。如果没有涉及Derived
的实例,则self
没有合适的Derived.virtual
,因此当然无法调用它。
答案 1 :(得分:4)
这并非不可能 - 实际上有一种解决方法,你不必传递函数或类似的东西。我自己正在开展一个项目,这个问题出现了。这是解决方案:
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()
答案 2 :(得分:-1)
好的,我刚刚传递了虚拟()的实例,我需要func()
class Base(object):
attr1 = ''
attr2 = ''
def __init__(self):
pass
def virtual(self):
pass
def func(self, cb):
print "%s, %s" % (self.attr1, self.attr2)
cb()
class Derived(Base):
attr1 = 'I am in class Derived'
attr2 = 'blah blah'
def virtual(self):
# do stuff...
# do stuff...
d = Derived()
d.func(d.virtual)