我试图将一些函数放在一起,并为此尝试了一个 Python 数据类。我无法想出或找到如何为数据类中的函数分配类型。
在下面的示例中,我使用了一个虚拟类型 int
,但我应该正确使用的不是 int
?
from dataclasses import dataclass
inc = lambda x : x+1
@dataclass
class Holder:
func: int # but I need a better type signature here
h = Holder(inc)
assert h.func(1) == 2
最佳答案
您应该使用 Callable
类型
from typing import Callable
@dataclass
class Holder:
func: Callable[[int], int]
关于python - 函数可以是 Python 数据类成员吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60643344/