Python对象包装器

 zero__ 发布于 2023-01-14 15:59
  • php
  • 我正在尝试创建一个行为类似于包装对象的包装类.到目前为止,我已经提出以下代码:

    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似乎被执行.你知道为什么会这样吗?

    撰写答案
    今天,你开发时遇到什么问题呢?
    立即提问
    热门标签
    PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
    Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有