'Initialized variable not accessable inside of the class

class DemoClass:
    
    def __init__(self):
       self.name = "Marko"
 
    def some_method(self):
        print(self.name)
 
    print(self.name)   # NameError: name 'self' is not defined ???
 
 
my_object = DemoClass()

Why does this happen? Didn't I initialize the self.name variable in the init method which I think it means that it should be accessable in the entire class?



Solution 1:[1]

class DemoClass:
    
    def __init__(self):
       self.name = "Marko"
 
    def some_method(self):
        print(self.name)
     
      
my_object = DemoClass()

my_object.some_method()

do like this bro then only you can print the name.

Solution 2:[2]

You call the print() function with a class attribute (name) as argument. Even though the attribute is defined when Python executes the print() line, the class attributes exist in the local scope of the class and are accessible only to the class members or through the class namespace (e.g. my_object.name in a different scope where my_object is defined).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 quamrana
Solution 2 Victor Sandoval