Completely wrap an object in Python

后端 未结 6 1052
太阳男子
太阳男子 2020-12-23 09:33

I am wanting to completely wrap an object so that all attribute and method requests get forwarded to the object it\'s wrapping, but also overriding any methods or variables

6条回答
  •  渐次进展
    2020-12-23 10:19

    Note: This answer is really old and might not work on modern Pythons. I believe it used to work on 2.6

    Start with this and mess with stuff in the loop to suit your needs:

    import inspect
    class Delegate(object):
        def __init__(self, implementation):
            self.__class__ = implementation.__class__
            for n, m in inspect.getmembers(implementation, callable):
                if not n.startswith('_'):
                    setattr(self, n, m)
    

    The ability to wrap not-new-style-objects is left as an exercise to the reader :)

提交回复
热议问题