Python在父类中使用派生类的方法? [英] Python using derived class's method in parent class?

查看:362
本文介绍了Python在父类中使用派生类的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以强制父类调用派生类的函数版本吗?

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

以及从中派生的类

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


推荐答案

如果你实例化ea 派生(比如 d = Derived()), .virtual d.func() 调用 Derived.virtual 。如果没有涉及 Derived 的实例,则 Derived.virtual没有合适的 self 所以当然不可能打电话给它。

If you instantiate a Derived (say d = Derived()), the .virtual that's called by d.func() is Derived.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.

这篇关于Python在父类中使用派生类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆