如何用Python ABC库重构Strawberry GraphQL公共类型以精简代码?
问题解答
可行,Strawberry 支持从普通 Python 类(包括 ABC 抽象类)继承类型注解字段,无需额外手动实现,就能达到减少重复代码的目的。
你需要调整类的继承关系,让 Home 和 Business 同时继承 Address 和 Contact 抽象类,修改后的代码如下:
from abc import ABC import strawberry # 假设 Address 是已定义的 Strawberry 类型 @strawberry.type class Address: # 示例字段,根据实际情况调整 street: str city: str class Contact(ABC): location: str description: str phone: int @strawberry.type class Home(Address, Contact): name: str @strawberry.type class Business(Address, Contact): name: str fax: int
关键说明:
Contact抽象类不需要添加@strawberry.type装饰器,Strawberry 会自动识别并继承其中的类型注解字段。- 多继承顺序不影响字段的提取(只要父类都是普通 Python 类或 Strawberry 类型)。
- 这种方式不会生成 GraphQL 接口,完全是 Python 层面的代码复用,符合你的需求。
内容的提问来源于stack exchange,提问作者ccsv
相关产品推荐
相关产品推荐

