Python在父类中使用派生类的方法?

标签 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.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()

最佳答案

如果您实例化一个Derived(例如d = Derived()),.virtual 将被d.func 调用() Derived.virtual。如果没有涉及 Derived 的实例,那么 Derived.virtual 就没有合适的 self ,当然不可能调用它。

关于Python在父类中使用派生类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2297843/

相关文章:

python - 比较分配给两个字典中一个键的多个值

python - 将列表的每个元素与第二个列表的每个元素连接起来

C++ 继承 "toString"

python - 我如何从 __init__ 调用属性 setter

Python 的属性装饰器没有按预期工作

python - 描述符和 python 提供的属性

python - 如何在python中通过paaver安装模块?

python - 如何将数字列表转换为字符串列表?

c++ - 抽象容器类和子类可以迭代吗?

java - 包中的基类和派生类