键入:如何将class作为参数传递?



我试图将一个类传递给Python中的函数,然后在函数中实例化它并返回它。到目前为止,这是有效的,但是一旦我尝试添加Python类型,我就会得到以下错误:

Expected no arguments to "object" constructor Pylance (reportGeneralTypeIssues)

下面是发生错误的最小示例:

from dataclasses import dataclass
from typing import Dict, Type, TypeVar
@dataclass
class Bar:
x: int
T = TypeVar('T')
def Foo(clazz: Type[T], kwargs: Dict[str, int]) -> T:
return clazz(**kwargs)  # --> Expected no arguments to "object" constructor
bar = Foo(Bar, {'x': 1})
print(type(bar))  # --> <class '__main__.Bar'>
谁能解释一下我在这里做错了什么?

可以使用强制转换,显式地告诉typeechecker表明,zz是对象的子类型可以接受命名参数。(可能有一个比Any更好的铸造目标但这是可行的)


from dataclasses import dataclass
from typing import Dict, Type, TypeVar, Any, cast
@dataclass
class Bar:
x: int
T = TypeVar('T')

def Foo(clazz: Type[T], kwargs: Dict[str, int]) -> T:
clazz = cast(Type[Any], clazz)
return clazz(**kwargs)  # --> Expected no arguments to "object" constructor
bar = Foo(Bar, {'x': 1})
print(type(bar))

最新更新