How to fake type with Python

前端 未结 6 824
生来不讨喜
生来不讨喜 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:46

    Here is a solution by using metaclass, but you need to modify the wrapped classes:

    >>> class DocumentWrapper:
        def __init__(self, wrapped_obj):
            self.wrapped_obj = wrapped_obj
    
    >>> class MetaWrapper(abc.ABCMeta):
        def __instancecheck__(self, instance):
            try:
                return isinstance(instance.wrapped_obj, self)
            except:
                return isinstance(instance, self)
    
    >>> class User(metaclass=MetaWrapper):
        pass
    
    >>> user=DocumentWrapper(User())
    >>> isinstance(user,User)
    True
    >>> class User2:
        pass
    
    >>> user2=DocumentWrapper(User2())
    >>> isinstance(user2,User2)
    False
    

提交回复
热议问题