我正在尝试创建一个包装类,其行为几乎与被包装的对象相同。到目前为止,我已经想出了以下代码:
import functools
import types
method_wrapper = type((None).__str__)
class Box:
def __new__(cls, obj):
attrs = {}
attr_names = dir(obj)
for attr_name in attr_names:
attr = obj.__getattribute__(attr_name)
if isinstance(attr, (types.MethodType, method_wrapper)):
"Attr is a bound method, ignore self"
@functools.wraps(attr)
def wrapped_attr(self, *args, **kwargs):
return attr(*args, **kwargs)
attrs[attr_name] = wrapped_attr
elif isinstance(attr, types.FunctionType):
"attr is a static method"
attrs[attr_name] = staticmethod(attr)
else:
"attr is a property"
attrs[attr_name] = attr
cls = type(type(obj).__name__,
(cls, type(obj)),
attrs)
return object.__new__(cls)
我尝试使用以下内容进行测试:
if __name__ == '__main__':
x=Box(object())
然而,它会出现以下错误信息:
TypeError: __init__() should return None, not 'NotImplementedType'
__init__
被正确地调用,使用了 isinstance(attr, (types.MethodType, method_wrapper))
,并且似乎执行了 wrapped_attr
。你有任何想法为什么会发生这种情况吗?