【问题标题】:Python using derived class's method in parent class?Python在父类中使用派生类的方法?
【发布时间】:2011-01-18 20:43:27
【问题描述】:

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

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

【问题讨论】:

  • 抱歉,把问题改得不那么含糊了
  • 使用 python 2.6.4 并将 print 放入派生的 virtual - 它使用派生的虚拟函数 - 而不是 Base
  • 是什么让你认为它在调用 Base::virtual()?

标签: python inheritance new-style-class


【解决方案1】:

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

【讨论】:

  • 你的权利当然……又太快了。这几天经常发生在我身上;-(
  • 我更改了问题以更好地解释我的意思
  • 保罗,你所说的不可能发生(使用你显示的代码)。运行您显示的代码,使用print "this is Derived.virtual!" 作为Derived.virtual 的主体,当然会打印出这个字符串(当然是在I am in class Derived, blah blah 字符串之后)。您的错误必须在您未显示的代码的其他部分中。
【解决方案2】:

这并非不可能——实际上有一种解决方法,您不必传入函数或类似的东西。我自己正在做一个项目,这个确切的问题出现了。这是解决方案:


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-23
    • 2018-10-12
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 2014-09-05
    • 2020-03-30
    • 1970-01-01
    相关资源
    最近更新 更多