[Python] Why is there no attribute (__orig_class__) on instantiation time? [duplicate]

Discussão em 'Python' iniciado por Stack, Janeiro 30, 2025.

  1. Stack

    Stack Membro Participativo

    In Python 3.10, there is no __orig_class__ attribute when an object is creating on intialization. Why isn't this attribute present during object creation? I'm just curious to understand why.

    sample:

    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()


    result:


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


    After instancing:
    <class 'int'>



    It was answered on https://stackoverflow.com/a/60984681/12557033


    The timing of the orig_class assignment varies by Python version, but currently, it's set after normal object construction has already finished. You will not be able to inspect orig_class during init or new.
    ​

    Continue reading...

Compartilhe esta Página