1
0

81_dataclasses.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from dataclasses import dataclass, asdict
  2. @dataclass
  3. class A:
  4. x: int
  5. y: str = '123'
  6. assert repr(A(1)) == "A(x=1, y='123')"
  7. assert repr(A(x=3)) == "A(x=3, y='123')"
  8. assert repr(A(1, '555')) == "A(x=1, y='555')"
  9. assert repr(A(x=7, y='555')) == "A(x=7, y='555')"
  10. assert asdict(A(1, '555')) == {'x': 1, 'y': '555'}
  11. assert A(1, 'N') == A(1, 'N')
  12. assert A(1, 'N') != A(1, 'M')
  13. #################
  14. @dataclass
  15. class Base:
  16. i: int
  17. j: int
  18. class Derived(Base):
  19. k: str = 'default'
  20. def sum(self):
  21. return self.i + self.j
  22. d = Derived(1, 2)
  23. assert d.i == 1
  24. assert d.j == 2
  25. assert d.k == 'default'
  26. assert d.sum() == 3
  27. @dataclass
  28. class PrimaryForceConfig:
  29. # 风场图
  30. planetary_wind: 'str'
  31. local_wind: int
  32. # 地壳运动(含地震带/地形生成)
  33. geothermal_activity: int
  34. # 太阳辐射标量场
  35. solar_radiation: int
  36. # 水汽场
  37. planetary_humidity: int
  38. config = PrimaryForceConfig(
  39. planetary_wind = 'default',
  40. local_wind = 1,
  41. geothermal_activity = 2,
  42. solar_radiation = 3,
  43. planetary_humidity = 4
  44. )
  45. assert config.planetary_wind == 'default'