我正在尝试创建一个行为类似于包装对象的包装类.到目前为止,我已经提出以下代码:
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
似乎被执行.你知道为什么会这样吗?