【问题标题】:Python 3.7: I want to pass the whole class as variable, how to use type hint to indicate the variable is a class? [duplicate]Python 3.7:我想将整个类作为变量传递,如何使用类型提示来指示变量是一个类? [复制]
【发布时间】:2020-03-13 17:05:19
【问题描述】:

示例代码:

def __init__(self, input_retailer, pull_gen_fun, login_class: typing.ClassVar):
    self.input_retailer = input_retailer
    self.pull_gen_fun = pull_gen_fun
    self.login_class = login_class

我认为 typing.ClassVar 不适合这种情况吗?

【问题讨论】:

  • 为什么不使用type?所有* 类对象都是内置 type 的子类。 (*ingoring 元类使用)

标签: python-3.x type-hinting


【解决方案1】:

一般来说,Python中的所有类对象都是内置type的子类:

class T:
    pass

print(type(T))              # outputs "<class 'type'>
print(isinstance(T, type))  # outputs "True"

如果您想基本上接受login_class 的任何类对象,使用type 对其进行注释是可行的方法:

def __init__(self, input_retailer, pull_gen_fun, login_class: type):
    ...

【讨论】:

    【解决方案2】:

    请检查这个。这就是你想要的?

    from typing import ClassVar
    
    
    def __init__(self, input_retailer, pull_gen_fun, login_class: ClassVar):
        self.input_retailer = input_retailer
        self.pull_gen_fun = pull_gen_fun
        self.login_class = login_class
    

    【讨论】:

    • 你仍然使用ClassVar。这与 OP 的解决方案有何不同?
    • OP 正在尝试使用 typing.ClassVar,但出现错误。他应该进口。
    • 您误解了 OP 的问题。他们的问题与NameError 无关。他们在问什么类型提示适合类对象,并指出typing.ClassVar 的文档表明它不适合这种用途。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 2014-01-03
    相关资源
    最近更新 更多