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()
>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.