Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I can't refer to class variable from nested class?

In simple case I can call teacher in loh function:

class Student:
   teacher = 'Mrs. Jones'

   def __init__(self, name):
       self.name = name
    
def loh():
  print(Student.teacher)

loh()

### Mrs. Jones

But, If I try to do that next way, I got mistake "not defined". Why?

class Student:
  class UnderStudent:
    teacher = 'Mrs. Jones'
  def f():
    print(UnderStudent.teacher)
  f()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

f tries to lookup UnderStudent in the global scope, but the name isn’t defined there; it’s only defined in the namespace of the class statement, which turns the name into a class attribute.

class Student:
    class UnderStudent:
        teacher = 'Mrs.Jones'
    def f(self):
        print(self.UnderStudent.teacher)
        # or print(Student.UnderStudent.teacher)

Nested classes are rare in Python, as there is no restriction on having multiple top-level classes in the same file as in some other languages.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading