Python Nested Class
What I want to do, is to have a hierarchically organized Python Class
. I wanted to pass the outer class
instance vatible to inner class
. Like:
1 | class Outer(object): |
But this can not work. The only solution is to instance outer class
again in inner class
. It will make the code looks like nested class, but actually there are two outer class objects
.
1 | class Outer(object): |
The best way to write nested class, is to avoid it.
The methods of a nested class cannot directly access the instance attributes of the outer class.
Note that it is not necessarily the case that an instance of the outer class exists even when you have created an instance of the inner class.
In fact, it is often recommended against using nested classes, since the nesting does not imply any particular relationship between the inner and outer classes.
Reference:
[1] Access outer class from inner class in python
[2] In nested classes, how to access outer class’s elements from nested class in Python?