【问题标题】:Typing: How to pass class as a parameter?打字:如何将类作为参数传递?
【发布时间】:2021-03-10 23:14:46
【问题描述】:

我试图将一个类传递给 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'>

有人可以向我解释我在这里做错了什么吗?

【问题讨论】:

  • 简而言之,注释声称这适用于所有类型和所有参数,而实际上它显然不是。
  • @MisterMiyagi 谢谢你的解释。那讲得通。你能告诉我我需要调整什么才能让它工作吗?
  • 你对类型有什么限制吗?
  • 我相信您应该将 Foo 定义为:def Foo(clazz: Type, kwargs: Dict[str, int]) -&gt; T: ...。检查这个答案:stackoverflow.com/a/60457872/286807

标签: python python-3.x python-typing


【解决方案1】:

它可以与 cast 一起工作,明确告诉 clazz 是对象子类型的类型检查器 可以接受命名参数。 (可能有 比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))

【讨论】:

    猜你喜欢
    • 2012-10-18
    • 2021-05-09
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多