【问题标题】:Python 3.6 types: Using variable before assignment [duplicate]Python 3.6 类型:在赋值前使用变量 [重复]
【发布时间】:2018-11-02 13:33:57
【问题描述】:

新的类型/提示/赋值方式很酷,但我不知道如何让这么简单的事情发挥作用:

class MyContainer:
    def addMyItem(self, item:MyItem):
        pass

class MyItem:
    def __init__(self, container:MyContainer):
        pass

它抛出一个错误:Using variable 'MyItem' before assignment。 到目前为止,我发现的最好但超级丑陋的解决方法是:

class MyContainer:
    def addMyItem(self, untypeditem):
        item:MyItem=untypeditem
        pass

class MyItem:
    def __init__(self, container:MyContainer):
        pass

请告诉我,#1 原则 Beautiful is better than ugly 的语言可以更好地解决这个常见的打字问题

【问题讨论】:

    标签: python python-3.x types


    【解决方案1】:

    前向引用只是引用名称的字符串(因为它在模块中可见)。

    class MyContainer:
        def addMyItem(self, item: 'MyItem'):
            pass
    
    class MyItem:
        def __init__(self, container: 'MyContainer'):
            pass
    

    如果您需要从其他地方导入名称(并且您只需要名称进行类型检查,或者如果它可能导致循环导入),您可以使用

    import typing
    
    if typing.TYPE_CHECKING:
        from foo import Thing
    

    TYPE_CHECKING is true only when a type checker is running (i.e. your code is not being evaluated for execution).

    【讨论】:

    • 不能说真的很漂亮,但我刚刚测试过,它可以工作!谢谢你,亲爱的先生!
    • 我不知道,我认为它对于动态语言来说已经很漂亮了 :) 不客气!
    • typescript 也是动态的,但它是这样工作的。我认为这个问题通常可以通过提升来解决
    猜你喜欢
    • 2021-07-30
    • 2013-09-13
    • 1970-01-01
    • 2017-12-18
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    相关资源
    最近更新 更多