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
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.
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.
Java inner class is associated with the object of the class and they can access all the variables and methods of the outer 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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With