python - 是否有一种机制可以通过引用调用方法并调用正确的子类的方法?
问题描述
在给定方法的引用的情况下,我想在子类的实例上调用带有参数的方法。问题:哪个方法是动态的,并且是父类的(未绑定)方法之一。
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
解决方案
推荐阅读
- python - Python3 __init__.py 如何存储包信息?
- java - Android Java Play gif 只播放一次
- c++builder - 更改线序时,网格内 FDQuery 的 Refresh() 函数似乎不起作用
- excel - Excel VBA 宏 - 类范围的复制方法失败
- c# - 是否可以在不加载 EF6 的情况下修改实体上的导航集合?
- javascript - Quill.js 和段落
- ios - 使用 foreach 的标签创建多个图像视图
- java - Hibernate Native SQL 返回一些空值而不是部分填充的对象
- mpi - 需要使用 Pin Tool 运行应用程序。该应用程序是一个 mpi 应用程序
- angular - Angular:属性的初始化问题