python - 如何“包装”对象以自动调用超类方法而不是覆盖方法?
问题描述
考虑:
class A(object):
def f(self): print("A")
class B(A):
def f(self): print("B")
b = B()
我可以A.f
通过以下方式调用b
:
A.f(b)
有没有一种简单的方法来“包装”b
这样wrap(b).f()
需要A.f
any f
?
解决方案
这是我的解决方案,它从最上层的基类复制方法:
import types, copy
def get_all_method_names(clazz):
return [func for func in dir(clazz) if callable(getattr(clazz, func))]
def wrap(obj):
obj = copy.copy(obj)
obj_clazz = obj.__class__
base_clazz = obj_clazz.__bases__[-1] # the one which directly inherits from object
base_methods = get_all_method_names(base_clazz) # list of all method names in base_clazz
for base_method_name in base_methods:
base_method = getattr(base_clazz, base_method_name) # get the method object
if isinstance(base_method, types.FunctionType): # skip dunder methods like __class__, __init__
setattr(obj, base_method_name, base_method) # copy it into our object
return obj
# class declaration from question here
wrapped_b = wrap(b)
wrapped_b.f(wrapped_b) # prints A, unfortunately we have to pass the self parameter explicitly
b.f() # prints B, proof that the original object is untouched
推荐阅读
- json - 通过 PowerShell 读取 JSON 文件
- android - 如何验证设备通讯录中的电话号码是否为手机(手机)?
- java - CloudsimSDN 错误:无法找到或加载主类 org.cloudbus.cloudsim.sdn.example
- python - 当我尝试使用切换到窗口来查找和处理元素时,会显示元素未找到错误
- c# - C# DNS 服务器重定向
- python - 错误缺少 1 个必需的位置参数 python 和线程
- linux - 如何更改 Linux 目录中文件的默认权限?
- html - CodeSandbox.io标签未加载图像
- ocr - Google Vision API - 我们能否在检测文档文本中包含自定义预处理逻辑并将其直接用作 Vision API
- web - 什么是最推荐的网络 360 度视频播放器?