Home > Back-end >  Accessing a variable within a nested function of the same class
Accessing a variable within a nested function of the same class

Time:12-25

I am trying to access variable within function_3 - how should I go about doing this?

class A:
    def function_1(self):
        
        def function_2(self):
            self.variable = 'Hello'
        function_2(self)
    
    function_1(self)

    def function_3(self):
        print(self.variable)
    
    function_3(self)

CodePudding user response:

The name self from here def function_2(self): shadows name self from here def function_1(self):

class A:
    def function_1(self):
        def function_2(self): # Here name `self` shadows name `self` from previous line
            self.variable = 'Hello'

        function_2(self)

    function_1(self) # Here you have no `self` variable

    def function_3(self):
        print(self.variable)

    function_3(self) # Here you have no `self` variable too

I think you want to achieve this behavior

class A:
    def function_1(self):
        def function_2(x):
            x.variable = 'Hello'

        function_2(self)

    def function_3(self):
        print(self.variable)


a = A()
a.function_1()
a.function_3()
> Hello

CodePudding user response:

Shout out if I misunderstood what you want to do, but it looks like you need to create an instance of class A, with A(), and then calling function_1 and function_3 on that instance. Pardon all the jargon, but I hope you can learn from example below:

class A:
    def function_1(self):
        def function_2(self):
            self.variable = 'Hello'

        function_2(self)


    def function_3(self):
        print(self.variable)



a = A()

a.function_1()
a.function_3()
  • Related