python-3.xfunctionclassnested

Nested Function in a Class, Python


I am trying to have Nested function inside a class. Here is my code

class big():
        def __init__(self):
        self.mas = "hello"
    
    def update(self):
        
        def output(self):
            print(self.mas)
        
        self.output()
        
thing = big()

thing.update()

However when it runs I get an error that output is not defined. How can i run the output function inside the update function?


Solution

  • Just call it as output(), without self. The way you've defined it, it basically is a local variable inside your update method, not an attribute of the class.

    class big():
        def __init__(self):
            self.mas = "hello"
    
        def update(self):
            def output():
                print(self.mas)
    
            output()
    
    thing = big()
    
    thing.update()