How to fake type with Python

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

    You can use the __instancecheck__ magic method to override the default isinstance behaviour:

    @classmethod
    def __instancecheck__(cls, instance):
        return isinstance(instance, User)
    

    This is only if you want your object to be a transparent wrapper; that is, if you want a DocumentWrapper to behave like a User. Otherwise, just expose the wrapped class as an attribute.

    This is a Python 3 addition; it came with abstract base classes. You can't do the same in Python 2.

提交回复
热议问题