首页 > 解决方案 > 是否有一种机制可以通过引用调用方法并调用正确的子类的方法?

问题描述

在给定方法的引用的情况下,我想在子类的实例上调用带有参数的方法。问题:哪个方法是动态的,并且是父类的(未绑定)方法之一。

class Parent:
    def method(self, x):
        print(f'Parent:foo called with {x}')

    def another(self, x):
        pass

class Child(Parent):
    def method(self, x):
        print(f'Child:foo called with {x}')

    def another(self, x):
        pass

# Change this
def problem_func(target: Parent, ref):
    meth, args = ref
    meth(target, args)

c = Child()
# Change this too
ref = (Parent.method, 42)
problem_func(c, ref)

上面打印了'Parent:foo call with 42'。我想要一个打印 'Child:foo call with 42' 的解决方案。

本质上,我想要一种将方法绑定到实例并让它遵循 Python 继承/MRO 规则的方法。更好的是,我想要一个包含这个和一些论点的闭包,但这可能要求太多了。

显然,我可以将 ref 更改为,(Child.method, 42)但这违背了目的。关键是 Parent 有多个子类,我将遍历这些子类,并且我想将“相同”方法(具有适当的覆盖行为)应用于所有子类。

我发现的一种解决方案是替换meth(target, args)getattr(target, meth.__name__)(args). 我正在寻找一个内置的答案。

编辑:本质上,我正在寻找与 C++ 中指向成员的指针的等价物。见https://stackoverflow.com/a/60023/6518334

标签: pythonpython-3.xinheritancemethods

解决方案


推荐阅读