什么是Python中的协议(a.k.a.结构子类型)?

时间:2016-11-28 13:50:06

标签: python python-3.x subtyping

from typing import SupportsInt
class C1():
    def __int__(self) -> int:
        return 42
class C2(C1):
    pass


>>>c = C2()
>>>print(int(c))
42
>>>print(isinstance(c, C1))
True

>>> type(typing.SupportsInt)
<class 'typing._ProtocolMeta'>

但为此它失败了

>>> isinstance(5, typing.SupportsInt)
...
TypeError: Protocols cannot be used with isinstance().

有一个类似的问题,但没有答案

protocols-cannot-be-used-with-isinstance-why-not

0 个答案:

没有答案