有没有一种方法可以安全地对协议子类的 python 类进行类型检查?
\n如果我定义具有特定方法函数签名的协议,则隐式子类必须定义具有兼容签名的方法:
\n# protocols.py\n\nfrom abc import abstractmethod\nfrom dataclasses import dataclass\nfrom typing import Protocol\n\nclass SupportsPublish(Protocol):\n @abstractmethod\n def publish(self, topic: str):\n ...\n\ndef publish(m: SupportsPublish):\n m.publish("topic")\n\n@dataclass\nclass Publishable:\n foo: str = "bar"\n\n def publish(self):\n print(self)\n\npublish(Publishable())\n\n# \xe2\x9c\x97 mypy protocols.py \n# protocols.py:24: error: Argument 1 to "publish" has incompatible type "Publishable"; expected "SupportsPublish" [arg-type]\n# protocols.py:24: note: Following member(s) of "Publishable" have conflicts:\n# protocols.py:24: note: Expected:\n# protocols.py:24: note: def publish(self, topic: str) -> Any\n# protocols.py:24: note: Got:\n# protocols.py:24: note: def publish(self) -> Any\n# …Run Code Online (Sandbox Code Playgroud)