使用
typing.Protocol
:
from typing import Protocol
class Foo(Protocol):
def do_stuff(self) -> str: ...
class Bar:
def do_stuff(self) -> str:
return "hello"
def some_function(obj: Foo):
print(obj.do_stuff())
some_function(Bar()) # ok
之间的区别
Protocol
和
ABC
您可以实现一个协议,而无需显式继承它
Bar
被视为
Foo
mypy,尽管它不是
Foo公司
.
如果传递的类型未实现协议,则会出现错误,例如:
class Baz:
def do_stuff(self) -> int:
return 42
some_function(Baz())
# error: Argument 1 to "some_function" has incompatible type "Baz"; expected "Foo"
# note: Following member(s) of "Baz" have conflicts:
# note: Expected:
# note: def do_stuff(self) -> str
# note: Got:
# note: def do_stuff(self) -> int