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

Python泛型类实例化时__init__内无法访问__orig_class__属性的原因

Python泛型类实例化时__init__内无法访问__orig_class__属性的原因

你遇到的这个问题其实是Python中__orig_class__属性的赋值时机导致的,咱们先看你给出的测试代码:

from typing import Generic, TypeVar

T = TypeVar('T')

class TryToGetTypeParameter(Generic[T]):
    def __init__(self):
        try:
            print("On instancing:")
            self._show_type_parameter()
        except Exception as e:
            print(e)
            print("\n")
            
    def _show_type_parameter(self):
        print(self.__orig_class__.__args__[0])
        print("\n")
        
    def show_type_parameter(self):
        print("After instancing:")
        self._show_type_parameter()
        
        
print("\n")
instanced = TryToGetTypeParameter[int]()
instanced.show_type_parameter()

运行这段代码后,得到的结果是:

On instancing:
'TryToGetTypeParameter' object has no attribute '__orig_class__'


After instancing:
<class 'int'>

这个现象的原因有明确的解释:

__orig_class__的赋值时机因Python版本而异,但目前它是在常规对象构造完成之后才被设置的。你无法在__init__或__new__方法执行期间访问__orig_class__。

就像你的代码展示的那样:在__init__执行时,Python还没把__orig_class__属性绑定到实例上,所以会抛出属性不存在的错误;而当整个实例化流程完成后,这个属性已经被正确设置,此时调用show_type_parameter就能正常获取到泛型的类型参数int了。

备注:内容来源于stack exchange,提问作者KLc3088

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 15:24:31