gpt4 book ai didi

python - 如何 "wrap"对象自动调用父类(super class)方法而不是重写方法?

转载 作者:行者123 更新时间:2023-12-02 08:17:54 25 4
gpt4 key购买 nike

考虑:

class A(object):
def f(self): print("A")

class B(A):
def f(self): print("B")

b = B()

我可以通过执行以下操作在 b 上调用 A.f:

A.f(b)

是否有一种简单的方法来“包装”b,以便 wrap(b).f() 为任何 调用 A.f >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

关于python - 如何 "wrap"对象自动调用父类(super class)方法而不是重写方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59356670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com