在Python中访问内部类内部的外部类变量
我正在尝试使用嵌套类在 Python 中实现以下结构:
class class1:
a1 = 1
class class2:
a2 = 2
class class3:
a3 = 3
print(class1.a1) #prints 1
print(class1.class2.a2) #prints 2
print(class1.class2.class3.a3) #prints 3
到目前为止,它按预期工作。但是当我将“a2 = 2”更改为“a2 = class1.a1 + 1”时,我收到错误“NameError:名称'class1'未定义”
class class1:
a1 = 1
class class2:
a2 = class1.a1 + 1
class class3:
a3 = 3
print(class1.a1)
print(class1.class2.a2)
print(class1.class2.class3.a3)
NameError: name 'class1' is not defined
执行此操作的正确方法是什么?我知道在 Python 中通常避免使用嵌套类,但是这个点符号 (class1.class2.a2) 对于我正在从事的项目非常重要。
编辑: 为了将事情放在上下文中,我想要做的是将 XML 文件解析为对象,以便我可以访问它的字段。它具有以下结构:
<CTe xmlns="http://www.portalfiscal.inf.br/cte">
<infCte versao="3.00">
<compl>
<xCaracAd>Normal</xCaracAd>
<xObs>DOC TRANSP: 35576713</xObs>
<ObsCont xCampo="DT">
<xTexto>35576713</xTexto>
</ObsCont>
</compl>
例如,我希望能够使用 infCte.compl.ObsCont.xTexto 提取“xTexto”字段。
实际上,我还可以选择使用 JavaScript 来完成这个项目,因此使用这种语言的解决方案也将受到赞赏。
I'm trying to implement the following structure in Python using nested classes:
class class1:
a1 = 1
class class2:
a2 = 2
class class3:
a3 = 3
print(class1.a1) #prints 1
print(class1.class2.a2) #prints 2
print(class1.class2.class3.a3) #prints 3
So far, it works as intended. But as I change "a2 = 2" to "a2 = class1.a1 + 1", I get error "NameError: name 'class1' is not defined"
class class1:
a1 = 1
class class2:
a2 = class1.a1 + 1
class class3:
a3 = 3
print(class1.a1)
print(class1.class2.a2)
print(class1.class2.class3.a3)
NameError: name 'class1' is not defined
What is the correct way of doing this? I know that nested classes are usually avoided in Python, but this dot notation (class1.class2.a2) is very important for the project I'm working on.
Edit:
To put things in context, what I'm trying to do is parsing an XML file to an object so I can access its fields. It has the following structure:
<CTe xmlns="http://www.portalfiscal.inf.br/cte">
<infCte versao="3.00">
<compl>
<xCaracAd>Normal</xCaracAd>
<xObs>DOC TRANSP: 35576713</xObs>
<ObsCont xCampo="DT">
<xTexto>35576713</xTexto>
</ObsCont>
</compl>
So, for example, I want to be able to extract the "xTexto" field by using infCte.compl.ObsCont.xTexto.
Actually, I also have the option of JavaScript for this project, so solutions in this language would be appreciated as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论