Python 3.7类实例的静态字典

我正在重用一个流行的 C++ 习语,其中一个类包含一个类实例的静态字典:


class Zzz:

    elements = {}


    def __init__(self, name):

        self._name = name

        Zzz.elements[name] = self


    @staticmethod

    def list_instances():

        for k in Zzz.elements.items():

            print(k)

在我添加类型注释之前它工作正常,现在 python 抱怨 Zzz 是未知类型:NameError: name 'Zzz' is not defined


from typing import Dict


class Zzz:

    elements: Dict[str,Zzz] = {} <---- here


互换的青春
浏览 117回答 2
2回答

哈士奇WWW

您可以前向引用您的类型,将其定义为字符串。from typing import Dictclass Zzz:&nbsp; &nbsp; elements: Dict[str, 'Zzz']顺便编辑一下,你可以很容易地自动填充这个实现__init_subclass__()方法的静态字典。class Zzz:&nbsp; &nbsp; elements: Dict[str, 'Zzz'] = {}&nbsp; &nbsp; name: str&nbsp; &nbsp; def __init_subclass__(cls, **kw):&nbsp; &nbsp; &nbsp; &nbsp; cls.elements[cls.name] = clsclass ZzzImpl(Zzz):&nbsp; &nbsp; name = 'foo'assert Zzz.elements['foo'] is ZzzImpl

偶然的你

当时注释为“已读”,Zzz尚不存在。Python 3.7 仍然在定义时评估注释;在这种情况下,它仍然是未定义的。Pep563涵盖了这一点:from&nbsp;__futures__&nbsp;import&nbsp;annotations
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python