【问题标题】:Python typing allow object of a certain class in the __init__ of that same class [duplicate]Python键入允许同一类的__init__中某个类的对象[重复]
【发布时间】:2022-01-21 16:02:13
【问题描述】:

我正在尝试创建一个名为Theme 的类,其__init__ 函数允许传入另一个可能是Theme 类型的对象。但是当我尝试键入提示该类型的对象时如果允许,Python 会抛出错误,因为 Theme 尚未定义。这是代码,当我取出类型提示时有效:

from typing import Union


class Theme:

    def __init__(self, start: Union[dict, Theme, None] = None):
        if start is None:
            start = {}
        elif isinstance(start, Theme):
            start = start.dict
        self.dict = start

我得到的错误是:

Traceback (most recent call last):
  File "C:/Users/.../Test.py", line 4, in <module>
    class Theme:
  File "C:/Users/.../Test.py", line 6, in Theme
    def __init__(self, start: Union[dict, Theme, None] = None):
NameError: name 'Theme' is not defined

我有什么办法可以做到这一点,还是不可能,我不应该打扰?

【问题讨论】:

    标签: python python-typing typing


    【解决方案1】:

    您可以从__future__ 导入注释。我认为在 3.10 中这是默认可用的。

    from __future__ import annotations
    
    from typing import Optional
    
    
    class MyClass:
        def __init__(self, cls: Optional[MyClass]) -> None:
            if cls:
                print(isinstance(cls, MyClass))
    
    
    c = MyClass(None)
    b = MyClass(c)
    

    【讨论】:

    • 虽然这段代码可以回答这个问题,但最好包含一些上下文,解释它如何工作以及何时使用它。从长远来看,纯代码的答案没有用处。
    猜你喜欢
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 2014-07-07
    • 2017-03-21
    • 2017-12-04
    相关资源
    最近更新 更多