[Python] How may I instantiate a class of type hint in python?

Discussão em 'Python' iniciado por Stack, Julho 7, 2025.

  1. Stack

    Stack Membro Participativo

    I am new to python and am coming from C# and java. I want to instantiate a class of the type provided as type hint R as following

    from typing import (TypeVar, Generic)

    class BaseParams(object):
    def __init__(self) -> None:
    self.name = 'set-in-base-class'

    class ChildParams(BaseParams):
    def __init__(self) -> None:
    super().__init__()
    self.name = 'set-in-child-class'

    R = TypeVar('R', bound= BaseParams)

    class MyGeneric(Generic[R]):
    def __init__(self) -> None:
    super().__init__()
    def test(self):
    r = R() # how should I instantiate R here
    print(r.name)

    c = MyGeneric[ChildParams]()
    c.test()


    something like the following C# code

    class BaseParams
    {
    public BaseParams()
    {
    Name = "set-in-base-class";
    }
    public string Name { get; set; }
    }
    class ChildParams : BaseParams
    {
    public ChildParams()
    {
    Name = "set-in-child-class";
    }
    }
    class MyGenericClass<R> where R : BaseParams, new()
    {
    public void test()
    {
    var r = new R();
    Console.WriteLine(r.Name);
    }
    }


    I've made quite a lot search on how to do that in python and all the sources refer to a situation where we provide the type in a method or something like that. I wonder if it is possible to do that at all.

    would you please someone help me to have a workaround on this?

    Continue reading...

Compartilhe esta Página