1 回答

TA貢獻1735條經驗 獲得超5個贊
Protocol
可以使用。我在這里記錄它是因為我發現這是一個很難搜索的主題;特別是檢查屬性是否存在。
為了確保屬性的存在:
from typing import Protocol
class HasFoo(Protocol):? ? ?# Define what's required
? ? foo: int
class Foo:? ? ? ? ? ? ? ? ? # This class fulfills the protocol implicitly
? ? def __init__(self):
? ? ? ? self.foo = 1
class Bar:
? ? def __init__(self):? ? ?# This class fails to implicitly fulfill the protocol
? ? ? ? self.bar = 2
def foo_func(f: HasFoo):
? ? pass
foo_func(Foo())? ? ? ? ? ? ?# Type check succeeds
foo_func(Bar())? ? ? ? ? ? ?# Type check fails
請注意 后面的類型提示foo。該行必須在語法上有效,并且類型必須與所檢查屬性的推斷類型相匹配。typing.Any如果您關心 的存在foo而不是其類型,則可以用作占位符。
同樣,檢查方法也可以這樣做:
class HasFoo(Protocol):
? ? def foo(self):
? ? ? ? pass
class Foo:
? ? def foo(self):
? ? ? ? pass
? ??
class Bar:
? ? def bar(self):
? ? ? ? pass
def func(f: HasFoo):
? ? pass
func(Foo())? ? ? ? ? ? ?# Succeeds
func(Bar())? ? ? ? ? ? ?# Fails
類型檢查是通過Pycharm 2020.2.2.
添加回答
舉報