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.
You cannot refer to
MetaDataElementwhile it is being constructed, since it does not yet exist. Thus,fails because the very construction of
mapInitiator2TyperequiresMetaDataElementto 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
MetaDataElementin any yet un-interpreted piece of code, as inYou even have to refer to
MetaDataElement, here, becauseMD_TAGis not a kind of local variable whenmethod_of_MetaDataElement()is executed (MD_TAGwas only defined as a kind of local variable during class construction). Once the classMetaDataElementis created,MD_TAGis simply a class attribute, which is whymethod_of_MetaDataElement()must refer to it as such.