Python- get parent class function instant variables from within a nested class

109 Views Asked by At

I'm having a bit of a dilemma with Python nested classes. What i'm trying to do is get variables from a function at the top level of class A and use them in the sub class B. Something like this

 class A:
   def function_A():
      value = 5

      class B:
        def function_B(self):
            print (A.value)

This method below works if i turn the variable into a class variable like below but it doesn't do what i want:

 class A:
   value = 5

      class B:
        def function_B(self):
            print (A.value)

I'm guessing that this isn't possible so can anyone provide a workaround?

2

There are 2 best solutions below

0
On

The class A has no attribute value, because the value variable is defined inside the function_A function. Therefore you don't have to access value as an attribute of the class, but as a normal variable that you can access from class B, because it is in the same scope. You have to remove the A. before value

Example:

class A:
    def function_A():
        value = 5

        class B:
            def function_B():
                print (value)

        var = B
        var.function_B()

test = A
test.function_A()
0
On

The variable value is local to function_A, and exists only while that method is running. There is simply nothing to access when it's not executing, which will be the case when function_B is executing. In particular, in your first example it's not an attribute of A, or of any instance of A.

It's not clear from your code what you actually intend to do with such a value, so it's difficult to make further suggestions.