Python使用派生类';父类中的方法?
我可以强制父类调用派生类版本的函数吗Python使用派生类';父类中的方法?,python,inheritance,new-style-class,Python,Inheritance,New Style Class,我可以强制父类调用派生类版本的函数吗 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.virt
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()
如果实例化一个
派生的
(比如d=Derived()
),则由d.func()
调用的.virtual
就是派生的.virtual
。如果没有Derived
的实例,那么就没有适合Derived.virtual
的self
,因此当然不可能调用它。这不是不可能的——实际上有一种方法可以解决这个问题,您不必传入函数或类似的东西。我自己也在做一个项目,就是在这个项目中出现了这个确切的问题。以下是解决方案:
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()
当然是你的权利。。。我又太快了。这几天我经常碰到这种事-(为了更好地解释我的意思,我修改了问题,Paul,你所说的是不可能发生的(用你展示的代码)。运行你展示的代码,用
print“this is Derived.virtual!”
作为Derived.virtual
的主体,当然会准确地打印这个字符串(在我在课堂上派生之后,当然是废话废话)。您的错误一定在代码的其他部分,但您没有显示。很抱歉,使用python 2.6.4将问题更改为不太含糊,并将打印放在派生虚拟中-它使用派生虚拟函数-而不是Basewhat使您认为它调用的是Base::virtual()?