You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何明确函数参数可接收父类item的任意子类而非仅父类本身

Python 物品栏系统:明确标注参数支持父类及所有子类

首先纠正你代码里的一个小错误:additem方法中你把item类本身加入了列表,而不是传入的_item实例,应该改成self.items.append(_item)。

回到你的核心问题:在类型标注中明确参数可接收item的任意子类。其实Python的类型系统本身就支持子类实例赋值给父类类型标注的变量,所以你当前的_item : item标注已经可以接收weapon等所有item子类的实例。但如果想让标注更直观,明确表达“支持父类及所有子类”,可以用以下两种方式:

方式1:使用TypeVar绑定父类(推荐)

通过typing.TypeVar创建一个绑定到item的泛型类型,这样标注能清晰传达“任意item子类实例”的意图:

from typing import TypeVar, List

# 创建绑定到item的泛型类型
ItemType = TypeVar('ItemType', bound='item')

class item:
    def __init__(self, weight: int, cost: int, name: str):  # 纠正name的类型标注为str(你传入的是字符串"bow")
        self.weight = weight
        self.cost = cost
        self.name = name

class weapon(item):
    def __init__(self, attackinfo, _weight: int, _cost: int, _name: str):
        super().__init__(_weight, _cost, _name)
        self.attackinfo = attackinfo

class inventory:
    def __init__(self):
        self.items: List[ItemType] = []  # 列表用泛型标注更严谨
    
    def additem(self, _item: ItemType) -> None:
        self.items.append(_item)

inventory1 = inventory()
inventory1.additem(weapon({"dmg" : 3, "range" : 10}, 5, 5, "bow"))

方式2:直接标注父类(简洁标准)

如果不需要额外强调子类兼容性,直接标注item就足够,类型检查器(如mypy)会自动识别子类实例符合该类型:

from typing import List

class item:
    def __init__(self, weight: int, cost: int, name: str):
        self.weight = weight
        self.cost = cost
        self.name = name

class weapon(item):
    def __init__(self, attackinfo, _weight: int, _cost: int, _name: str):
        super().__init__(_weight, _cost, _name)
        self.attackinfo = attackinfo

class inventory:
    def __init__(self):
        self.items: List[item] = []
    
    def additem(self, _item: item) -> None:
        self.items.append(_item)

inventory1 = inventory()
inventory1.additem(weapon({"dmg" : 3, "range" : 10}, 5, 5, "bow"))

内容的提问来源于stack exchange,提问作者Kowaga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 23:29:54