Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

228
Visualizações
Accessing outer class variable inside inner class in Python

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.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda