Chr*_*uer 2 python oop python-typing
我有一些自动生成的代码,它定义了许多具有通用属性的类,例如不幸的是,它们没有基类、接口等。
class A:
errors = []
class B
errors = []
Run Code Online (Sandbox Code Playgroud)
我该如何描述一种类型?我不能轻易改变所有这些类型。
def validate(obj: ???):
if errors:
raise Exception("something wrong")
Run Code Online (Sandbox Code Playgroud)
您需要定义一个协议,该协议typing.Protocol在 Python 3.8 或更高版本中完成(早期版本可以Protocol在typing_extensions模块中找到。)
from typing import Protocol
class HasErrors(Protocol):
errors: list
# Requires an object whose type supports the HasErrors
# protocol, namely one with a list-valued class attribute
# named "errors"
def validate(obj: HasErrors):
if obj.errors:
raise Exception("something wrong")
class GoodClass:
errors: List[Any] = []
class BadClass1:
pass
class BadClass2:
errors: int = 3
validate(GoodClass()) # will pass
validate(BadClass1()) # will not pass; no errors attribute
validate(BadClass2()) # will not pass; errors attribute has wrong type
Run Code Online (Sandbox Code Playgroud)