使用Pydantic类定义参数类型时遇AttributeError问题求助
问题分析与修复方案
你的代码存在三个核心问题,都是混淆了TypeScript与Python/Pydantic的使用逻辑导致的:
1. 函数内实例属性访问错误
raise_exceptions函数里的args.User写法完全错误——args本身就是User类的实例,直接访问实例属性即可:
def raise_exceptions(args: User): print(args) # 直接读取实例的id和username属性 user_id, username = args.id, args.username return user_id, username
2. 测试传参方式错误
你试图用{User.id: 12345, User.username: 'test-username'}传参,但User.id是类的字段定义,不是字典的合法键。构造Pydantic模型实例有两种正确方式:
方式一:直接传入关键字参数
def test_raise_exceptions(): # 直接通过关键字参数创建User实例 response = raise_exceptions(args=User(id=12345, username='test-username')) print(response)
方式二:字典解包传参
如果习惯用字典组织数据,可以用解包语法:
def test_raise_exceptions(): user_data = {'id': 12345, 'username': 'test-username'} # 解包字典为关键字参数创建实例 response = raise_exceptions(args=User(**user_data)) print(response)
3. 错误原因说明
你遇到的AttributeError: id,是因为尝试访问User.id这个类属性,但Pydantic模型类不会把字段直接暴露为类属性,这和TypeScript的类型访问逻辑完全不同,混淆了类定义与实例属性的区别。
完整修复后代码
模型定义(保持不变)
from pydantic import BaseModel class User(BaseModel): id: int username: str
函数定义
def raise_exceptions(args: User): print(args) user_id, username = args.id, args.username return user_id, username
测试代码
def test_raise_exceptions(): response = raise_exceptions(args=User(id=12345, username='test-username')) print(response) # 输出结果:(12345, 'test-username')
内容的提问来源于stack exchange,提问作者aroe
相关产品推荐
相关产品推荐

