我对以下代码感到非常困惑:
import dataclasses
@dataclasses.dataclass()
class Base():
x: int = 100
@dataclasses.dataclass()
class Derived(Base):
x: int = 200
@dataclasses.dataclass()
class DerivedRaw(Base):
x = 300
base = Base()
derived = Derived()
derived_raw = DerivedRaw()
print(base.x)
print(derived.x)
print(derived_raw.x)
它打印的内容是:
100
200
100
我不明白为什么最后一个数字不是 300。为什么注释很重要?
这似乎是与
@dataclasses.dataclass()
的交互,如代码:
class Base():
x: int = 100
class DerivedRaw(Base):
x = 300
derived_raw = DerivedRaw()
print(derived_raw.x)
打印 300。