Home > Blockchain >  Initialized variable not accessable inside of the class
Initialized variable not accessable inside of the class

Time:04-09

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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related