如何在Python中创建并返回类型为T的新实例



是否可以在python中使用泛型创建一个T类型的新实例?我知道如何在C#中做到这一点,已经找到了很多例子,但找不到任何关于python的东西。例如:

public class Animal<T> where T : ISound, new(){
public T GetInstance()
{
return new T();
}}

有没有类似于上述C#代码段的python?

这就是我认为我的python代码需要的样子:

from typing import TypeVar, Generic
T = TypeVar('T'
class crud(Generic[T])
def create(self, endpoint: str, body, files=None) ->T:
url = self._build_url_str(endpoint)
res = self.http.post(url, json=body).json()
return T.__init__(res)

但我得到了TypeError:不允许使用单个约束。

我在谷歌上搜索了一下,发现什么都不起作用,或者似乎无关紧要。

此外,类型T具有解析构造函数中响应所需的内容,因此必须对其进行参数化。

如这里的答案所述,您可以执行以下操作:

class Animal(Generic[T]):
def get_instance(self) -> T:
return self.__orig_class__.__args__[0]()

最新更新