Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In nested classes, how to access outer class's elements from nested class in Python?

I have this scenario, where I need to ask a nested class to append items to a list in the outer class. Heres pseudocode thats similar to what Im trying to do. How would I go about getting it to work?

class Outer(object):
  outerlist = []
  class Inner(object):
    def __call__(self, arg1):
      outerlist.append(arg1)

if __name__ == "__main__":
  f = Outer()
  f.Inner("apple")
  f.Inner("orange")

  print f.outerlist()

This is what I hope to see - apple, orange

Details:
OS X, Python 2.7

like image 935
Sri Kadimisetty Avatar asked Dec 10 '12 09:12

Sri Kadimisetty


People also ask

Can nested class be accessed outside?

Unlike the non-static nested classes, the static nested class cannot directly access the instance variables or methods of the outer class. They can access them by referring to an object of a class.

How do you access the outer class method of an inner class?

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass. InnerClass innerObject = outerObject.

Can inner class access outer class variables?

Java inner class is associated with the object of the class and they can access all the variables and methods of the outer class.

Can we call outer class method in inner class?

You're first question (whether the inner class holds an instance of the outer class) was the relevant question; but the answer is yes, always.


2 Answers

This will have the desired result.

Notice the use of __new__ (line A). This means that instead of doing any construction stuff properly Inner just appends the list. Also, to access class properties of a containing class just use the outer class's name (line B).

Lastly see line C. the list is not a function. You had some extra brackets in your original code.

class Outer(object):
    outerlist = []
    class Inner(object):
        def __new__(self, arg1):                #A
            Outer.outerlist.append(arg1)        #B

f = Outer()
f.Inner("apple")
f.Inner("orange")
print f.outerlist                               #C
like image 156
Sheena Avatar answered Oct 05 '22 22:10

Sheena


You can only access the outer class with the full global name:

class Outer(object):
    outerlist = []
    class Inner(object):
        def __call__(self, arg1):
            Outer.outerlist.append(arg1)

In python, there generally is no need to nest classes in any case. There are use-cases where it makes sense to define a class in a function (to use scoped variabels), but rarely is there a need for nested classes.

like image 39
Martijn Pieters Avatar answered Oct 05 '22 23:10

Martijn Pieters