注:代码基于pydantic版本~1.10.x
pydantic版本2.x中可能有变化
from pydantic import BaseModel
class BaseFather(BaseModel):
name: str
age: int
class BaseSon(BaseFather):
tools: str # 定义 tools 字段
def __init__(self, tools: str, age: int, name: str):
# 这里必须给所有的,包括自己的
super().__init__(name=name, age=age, tools=tools)
self.func()
def func(self):
# 在这里定义方法的具体逻辑
print(f"Executing func() with tools={self.tools}")
class Father:
def __init__(self, name, age):
name = name
age = age
class Son(Father):
def __init__(self, name, age, tools):
super().__init__(name=name, age=age)
self.tools = tools
self.func()
def func(self):
# 在这里定义方法的具体逻辑
print(f"Executing func() with tools={self.tools}")
a = BaseSon(tools="poetry", age=30, name="libai")
# b = Son(tools="poetry", age=30, name="libai")