How to fake type with Python

前端 未结 6 821
生来不讨喜
生来不讨喜 2020-12-10 12:04

I recently developed a class named DocumentWrapper around some ORM document object in Python to transparently add some features to it without changing its inter

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-10 12:29

    Override __class__ in your wrapper class DocumentWrapper:

    class DocumentWrapper(object):
    
      @property
      def __class__(self):
        return User
    
    >>> isinstance(DocumentWrapper(), User)
    True
    

    This way no modifications to the wrapped class User are needed.

    Python Mock does the same (see mock.py:612 in mock-2.0.0, couldn't find sources online to link to, sorry).

提交回复
热议问题