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

如何在Python子类中继承typing.Optional类型的可选属性?

解决Python子类中Optional属性无法通过父类__init__设置的问题

问题根源

你的代码中,父类Test的__init__方法里使用get_type_hints(self)获取类型提示,但这个调用实际只会获取父类Test自身的属性类型,不会包含子类Test_inherit新增的symbol属性。当子类传入symbol参数时,父类处理kwargs会因为找不到对应的type hint而抛出KeyError。

修复方案

将父类中获取类型提示的代码改为基于实例的类(即type(self)),这样就能拿到当前实例所属类(包括子类)的所有类型提示,涵盖继承来的属性和子类新增的属性。

修改后的父类__init__核心代码:

type_hints = get_type_hints(type(self))  # 替换原来的get_type_hints(self)

完整修复代码

from typing import Optional
from typing import get_type_hints


class Test:
    name: str
    type: str
    units: Optional[str]
    
    def __init__(self, name, typ_, **kwargs) -> None:
        self.name = name
        self.type = typ_
        # 获取当前实例所属类的所有类型提示(含子类新增属性)
        type_hints = get_type_hints(type(self))
        for argname in kwargs:
            type_hint = type_hints[argname]
            if hasattr(type_hint, "__args__"):  # 处理Optional类型
                # 提取Optional中除None外的真实类型
                type_hint = next(t for t in type_hint.__args__ if not isinstance(t, type(None)))
            setattr(self, argname, type_hint(kwargs[argname]))


class Test_inherit(Test):
    TAG: str
    symbol: Optional[str]
    
    def __init__(self, name, typ_, **kwargs) -> None:
        self.TAG = 'Test_tag'
        super().__init__(name, typ_, **kwargs)


# 测试代码
test0 = Test('hallo', 'float')   
print(test0.name, test0.type)
test1 = Test('hallo', 'float', units='N')   
print(test1.name, test1.type, test1.units)
test2_0 = Test_inherit('hallo','float')
print(test2_0.name, test2_0.type)
test2_1 = Test_inherit('hallo','float', symbol='N')
print(test2_1.name, test2_1.type, test2_1.symbol)
test3 = Test_inherit('hallo','float', units='N')
print(test3.name, test3.type, test3.units)

运行结果

hallo float
hallo float N
hallo float
hallo float N
hallo float N

修改后,子类新增的Optional属性symbol可以正常通过kwargs传入并设置,同时父类的units属性在子类中也能正常使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:01:55