使用@dataclass属性,可以使用类似于结构的语法定义类.
from dataclasses import dataclass
@dataclass
class A:
a: int这大致相当于(它实际上添加了更多的方法):
class A:
def __init__(self, a: int):
self.a = a但是我发现没有@dataclass也可以做到这一点,但是它似乎并没有做任何事情:
class B:
a: int>>> B(1)
TypeError: B() takes no arguments
>>> B.a
AttributeError: type object 'B' has no attribute 'a'发布于 2022-10-07 14:18:41
在抓挠我的头一段时间后,我有了一个eureka时刻:类型提示是用于类型(或任何其他类型检查器),而不是解释器。因此,这意味着如果在一个类型为B的对象中有一个属性B,那么它应该是一个int。指定一个可能永远不存在的变量的类型有点奇怪,但您确实存在。
按以下方式运行:
class B:
a: int
b = B()
b.a = "s"et voilàerror: Incompatible types in assignment (expression has type "str", variable has type "int")
https://stackoverflow.com/questions/73988573
复制相似问题