Python - 从类主体内部引用类名
在Python中,我想要一个类属性,一个带有初始化值的字典。我编写了这段代码:
class MetaDataElement:
(MD_INVALID, MD_CATEGORY, MD_TAG) = range(3)
mapInitiator2Type = {'!':MetaDataElement.MD_CATEGORY,
'#':MetaDataElement.MD_TAG}
但是当我尝试运行此代码时,我收到一条错误消息“NameError:名称'MetaDataElement'未定义”。你能帮我吗?
提前致谢。
In Python, I want to have a class attribute, a dictionary, with initialized values. I wrote this code:
class MetaDataElement:
(MD_INVALID, MD_CATEGORY, MD_TAG) = range(3)
mapInitiator2Type = {'!':MetaDataElement.MD_CATEGORY,
'#':MetaDataElement.MD_TAG}
But when I try to run this code, I get an error message with "NameError: name 'MetaDataElement' is not defined". Could you help me?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法在构建时引用
MetaDataElement
,因为它还不存在。因此,失败是因为
mapInitiator2Type
的构造本身要求MetaDataElement
具有属性,而它还没有。您可以将常量MD_INVALID
等视为类构造的本地变量。这就是为什么以下内容有效,正如 icktoofay 所写的:但是,您可以在任何尚未解释的代码段中引用类
MetaDataElement
,就像您甚至have to这里参考
MetaDataElement
,因为执行method_of_MetaDataElement()
时,MD_TAG
不是一种局部变量(MD_TAG 仅在类构造期间被定义为一种局部变量)。创建
MetaDataElement
类后,MD_TAG
只是一个类属性,这就是method_of_MetaDataElement()
必须这样引用它的原因。You cannot refer to
MetaDataElement
while it is being constructed, since it does not yet exist. Thus,fails because the very construction of
mapInitiator2Type
requiresMetaDataElement
to have attributes, which it does not yet have. You can think of your constantsMD_INVALID
, etc. as variables that are local to the construction of your class. This is why the following works, as icktoofay wrote:However, you can refer to the class
MetaDataElement
in any yet un-interpreted piece of code, as inYou even have to refer to
MetaDataElement
, here, becauseMD_TAG
is not a kind of local variable whenmethod_of_MetaDataElement()
is executed (MD_TAG
was only defined as a kind of local variable during class construction). Once the classMetaDataElement
is created,MD_TAG
is simply a class attribute, which is whymethod_of_MetaDataElement()
must refer to it as such.首先,您使用的是旧式类。您可能应该使用新式类,如下所示:
注意
(object)
。但无论如何,只需在引用类属性时删除MetaDataElement.
即可。完成后会是这样的:First of all, you're using old-style classes. You should probably use new-style classes, like so:
Note the
(object)
. Anyway, though, simply remove theMetaDataElement.
when referring to the class attributes. This is what it'd look like when that's done: