假设我有一个类,其中一个属性有多种可能的类型,而一个函数仅适用于其中某些类型。
我如何类型提示该函数,以便它指定它只接受原始类接受的某些类型?
import dataclasses
@dataclasses.dataclass
class Foo:
a: int | str
def plus_1_a(foo: Foo) -> None:
"""This will only work if foo.a is an int, not a string."""
foo.a += 1
考虑使
Foo
泛型化于 a
的类型。
import dataclasses
from typing import Generic, TypeVar
T = TypeVar("T", int, str)
@dataclasses.dataclass
class Foo(Generic[T]):
a: T
def plus_1_a(foo: Foo[int]) -> None:
"""This will only work if foo.a is an int, not a string."""
foo.a += 1