Completely wrap an object in Python

后端 未结 6 1031
太阳男子
太阳男子 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:12

    __getattr__ has the advantage that it's only called when the attribute does not exist, so you should not need an explicit list -- anything you don't define will automatically get proxied.

    __setattr__ is trickier because it's always called. Make sure you use a superclass call or object.__setattr__ when setting your own attributes; using setattr() within __setattr__ will cause infinite recursion.

    The final bit, affecting isinstance, is very difficult. You can do it with an assigment to your wrapper instance's .__class__ variable (but this also overrides class dictionary resolution order), or by dynamically constructing your wrapper type using a metaclass. Since isinstance is so rare in Python code, it seems overkill to actually try to trick it.

    More information on special attribute access methods.

    Even more information on them, plus some help with metaclasses.

提交回复
热议问题