Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

230
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!