demo4_typeDict.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. # 1. 导入需要的类型
  2. from typing import TypedDict
  3. class SimpleState(TypedDict):
  4. input: str
  5. output: str
  6. # 2. 创建 SimpleState 类型的字典(就像普通字典一样)
  7. # state1 = SimpleState(input="hello", output="world")
  8. # print(state1)
  9. # print(type(state1))
  10. # # # 或者用等号赋值
  11. # # state2: SimpleState = {
  12. # # "input": "你好",
  13. # # "output": "世界"
  14. # # }
  15. #
  16. # # 3. 访问字段
  17. # print(state1["input"]) # 输出: hello
  18. #
  19. # # print(state2["output"]) # 输出: 世界
  20. #
  21. # # # 4. 修改字段(和普通字典完全一样)
  22. # state1["output"] = "Python"
  23. # print(state1) # 输出: {'input': 'hello', 'output': 'Python'}
  24. #
  25. # # 5. 演示类型检查的好处(如果你在使用 PyCharm / VSCode + Pylance)
  26. # 下面的代码会触发编辑器的警告(但运行时仍可执行,因为 Python 本身不强制类型)
  27. state3: SimpleState = {"input": 123, "output": "wrong"} # 警告:input 应该是 str,但给了 int
  28. print(f'state3-->{state3}')
  29. state4: SimpleState = {"input": "ok"} # 警告:缺少 output 字段
  30. print(f'state4-->{state4}')
  31. state5: SimpleState = {"input": "a", "output": "b", "extra": 1} # 警告:多出的字段 extra
  32. print(f'state5-->{state5}')