【问题标题】:Add features to all child classes in python module向python模块中的所有子类添加功能
【发布时间】:2016-06-24 21:11:50
【问题描述】:

我想更新 python 模块中的一些父类以向所有子类添加功能。该模块通过pip安装。

如果我可以修改父类,我只是给它添加方法。但是,我不应该编辑已安装的模块。 (按照我之前的discussion

如何在不编辑 pip 包目录中的文件的情况下向 python 包中的所有子类添加功能?

另一种方法是使用monkeypatching,但似乎太棘手了。

更新

具体情况是我想给Child1Child2添加通用方法,但是不能编辑Parent,因为它是pip包的一个类。

class Parent:
    ...

class Child1(Parent):
    ...

class Child2(Parent):
    ...

【问题讨论】:

  • 您是否尝试过创建另一个可以被 Child1 和 Child2 继承的父类?

标签: python inheritance metaprogramming


【解决方案1】:
class Parent:
    ...

class Mixin:
    def common_method (self, ...):
        ....

class Child1 (Parent, Mixin):
    ....

class Child2 (Parent, Mixin):
    ...

class Parent:
    ...

class Augmented (Parent):
    def common_method (self, ...):
        ....

class Child1 (Augmented):
    ....

class Child2 (Augmented):
    ...

【讨论】:

  • 对不起,我含糊其辞。 Child1 和 Child2 也在 pip 包中。所以,我不能编辑 Child1 和 Child2
【解决方案2】:

我不推荐这个,但你可以使用setattr

class Parent:
    age = 50

class Child(Parent):
    age = 20

def test(cls):
    print cls.age

setattr(Parent, 'some_func', classmethod(test))

Parent.some_func()
Child.some_func()

这个输出

50
20

【讨论】:

  • 这是猴子补丁,可能是最好的解决方案。我知道setattr(Parent, 'some_func', ...)Parent.some_func = ... 之间没有区别。
【解决方案3】:

如果模块不依赖 C 代码,我认为猴子补丁可能是唯一没有枚举子类并手动添加方法的解决方案。

test_module.py

class Parent(object):
    def __init__(self, name):
        self.name = name

class Child1(Parent): pass

class Child2(Parent): pass

other_file.py

from test_module import Parent, Child1, Child2

Parent.say = lambda self: self.name # monkey-patching

child1, child2 = Child1('Bob'), Child2('Larry')

print child1.say() # Bob
print child2.say() # Larry

您甚至可以在 child1child2 被实例化并且仍然可以访问它之后将方法添加到 Parent 。这也适用于新的子类。

class Subchild(Child1): pass

Subchild('Moe').say() # Moe

【讨论】:

    猜你喜欢
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2012-05-04
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多