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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Outer(object):
def __init__(self, outerObj):
self.obj = outerObj

def outerFunction():
# do something

class Inner(object):
def __init__(self):
self.varible = Outer.obj.varible

def innerFunction():
# do something else

# Usage: -----------------------------------
f = Outer(sth)
b = f.Inner()
b.innerFunction()

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
2
3
4
5
6
7
8
9
10
class Outer(object):
def some_method(self):
# do something

class _Inner(object):
def __init__(self, outer):
outer.some_method()

def Inner(self):
return Inner(self)

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?