How to fake/proxy a class in Python

前端 未结 3 648
花落未央
花落未央 2020-11-29 07:17

I wrote some wrapper which has another object as an attribute. This wrapper proxies (forwards) all attribute requests with __getattr__ and __setattr__

3条回答
  •  不知归路
    2020-11-29 08:00

    This problem is reasonably well addressed by this recipe:

    Object Proxying (Python recipe)

    The general idea you have to follow is that most methods on classes are accessed through some combination of __getattr__ and __getattribute__ either on the class itself, or on its metaclass, but this does not apply to python special methods, the ones that begin and end with double underscore, for those to be found, they must be actual methods on the actual class, no attribute proxying is possible.

    Which of those methods you must provide will obviously depend on which of those methods the proxied class itself offers. The special methods you need to provide for isinstance() are the __instancecheck__ and __subclasscheck__ methods. for repr() to work, you must also define an appropriate __repr__() on the proxy class itself.

提交回复
热议问题