# # 使用 isdigit() 方法检查整数字符串
# num_str = "12345"
# if num_str.isdigit():
# print("字符串可以转为数字")
# else:
# print("字符串不是数字字符串")
#
# # 使用 try-except 语句和 float() 函数检查数字字符串
# num_str = "3.14159"
# try:
# float(num_str)
# print("字符串可以转为数字")
# except ValueError:
# print("字符串不是数字字符串")
from pydantic import BaseModel
from typing import Optional
from typing import Union
import json
class Position(BaseModel):
name: str
level: int
class Department(BaseModel):
name: str
desc: str
pos: Position
class Person(BaseModel):
# name无默认值,是必填项
id: int
name: str
# name: Optional[str] # 类型为str,不填写默认设置为None
# 无默认值可以不填
age: int = 18 # 设置默认值
entry_time: Union[int, str] # 两种类型都可以
department: Department
# position: Position
pos = Position(name="python dev", level=3)
dep = Department(name="产研部", desc="产品研发", pos=pos)
p = Person(id=1, name="Tom", age=27, entry_time="2023-10-13", department=dep)
# p = Person()
print(
p.json()) # {"id": 1, "name": "Tom", "age": 27, "entry_time": "2023-10-13", "department": {"name": "\u4ea7\u7814\u90e8", "desc": "\u4ea7\u54c1\u7814\u53d1", "pos": {"name": "python dev", "level": 3}}}
print(
p.dict()) # {'id': 1, 'name': 'Tom', 'age': 27, 'entry_time': '2023-10-13', 'department': {'name': '产研部', 'desc': '产品研发', 'pos': {'name': 'python dev', 'level': 3}}}
print(json.dumps(p.dict(),
ensure_ascii=False)) # {"id": 1, "name": "Tom", "age": 27, "entry_time": "2023-10-13", "department": {"name": "产研部", "desc": "产品研发", "pos": {"name": "python dev", "level": 3}}}
# print(p.age)