Python从父类调用子方法

时间:2015-02-20 02:44:25

标签: python inheritance super

我正在使用yapsy为项目设置一些运行时插件。我从IPlugin抽象类派生了我自己的插件类型:

class MyPlugin(IPlugin):
    def __init__(self):
        # call IPlugin's constructor, to initialize is_activated, activate()
        # and deactivate().
        super(self.__class__, self).__init__()
        self.__is_installed = self.installed

    @property
    def installed():
        # this must be implemented in the plugin
        raise NotImplementedError("installed must be implemented by %s" % self)

插件看起来像这样:

from mypackage.plugin import MyPlugin

class TestPlugin(MyPlugin):
    @property
    def installed():
        return False

对self.installed的调用从installed调用MyPlugin方法,而不调用installed中被覆盖的TestPlugin方法。我一直在浏览有关python继承和super()的各种文档,但我没有看到(或理解)我需要的东西。有什么建议吗?

编辑:我写了一个简单的例子,以确认事情是按照我的方式运作的。应该自动调用子方法"#34;而不是父母的方法。既然不是,我认为它必定是yapsy正在做的事情。还是想弄清楚。

class Parent(object):
    def __init__(self):
        self.name = 'parent'
        print('%s\t\t Parent.__init__()' % self.name)

class Child(Parent):
    def __init__(self):
        self.name = 'child'

        # super doesn't overriding name
        print('%s\t\t Child.__init__()\t before super()' % self.name)
        super(Parent, self).__init__()
        print('%s\t\t Child.__init__()\t after super()' % self.name)

        # this does override name
        print('%s\t\t Child.__init__()\t before Parent.__init__()' % self.name)
        Parent.__init__(self)
        print('%s\t\t Child.__init__()\t after Parent.__init__()' % self.name)

        self.set_name()

    def set_name(self):
        print('%s\t\t Child.__init__()\t before Child.set_name()' % self.name)
        self.name = 'child'
        print('%s\t\t Child.__init__()\t after Child.set_name()' % self.name)


class Grandchild(Child):
    # when creating an instance of grandchild, this method is called and
    # Parent.set_name is not.
    def set_name(self):
        print('%s\t\t Grandchild.__init__()\t before Grandchild.set_name()' % self.name)
        self.name = 'grandchild'
        print('%s\t Grandchild.__init__()\t after Grandchild.set_name()' % self.name)


if __name__ == '__main__':
    p = Parent()
    c = Child()
    g = Grandchil

1 个答案:

答案 0 :(得分:0)

我正在看这个,我的解决方案就是这个

基础插件类

class PluginBase():

        def generate(self):
             print('PluginBase plugin(generate)')

        def generated_files(self):
            print('PluginBase plugin(generated files)')
            return {}

实际插件

from PluginBase import PluginBase
from yapsy.IPlugin import IPlugin

class Test(PluginBase, IPlugin):

    def generate(self):
         print('Test plugin(generate)')

    def generated_files(self):
        print('Test plugin(generated files)')
        return {'file1': 'some/path/to/file1',
                'file2': 'some/other/path/to/file2'}

因此,直接在您的实际插件类而不是祖先类

中继承IPlugin