Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

227
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda