There is not much sense in creating nested classes, although it is possible.
What you probably want is just an associated child object, as an attribute to instances of the OuterClass object.
A nested InnerClass, as asked, cannot know, and can't retrieve things from the outer class.
However, using the descriptor mechanisms, even its ready made implementation, the @property decorator, you can have associated objects of the innerclass built for free, and with a "natural knowledge" about its parent.
This is the pattern I believe can be useful for you:
class InnerClass:
def __init__(self, parent):
self.parent = parent
def get_parent_link(self):
return self.parent
class OuterClass:
@property
def child_obj(self):
# this if clause bellow will restrict one child instance of "inner"
# per "outter" instance. Just `return InnerClass(parent=self)`
# to create a new instance each time .child_obj is retrieved
# if desired
if not hasattr(self, "_inner"):
self._inner = InnerClass(parent=self)
return InnerClass(parent = self)
parent_obj = OuterClass()
child_obj = parent_obj.child_obj # like this - no parenthesis needed
child_obj.get_parent_link()
However, what you are asking for is possible using metaclasses and the descriptor protocol. It is just not useful - but for entertainment purposes, you can write:
from copy import copy
class Meta(type):
def __get__(cls, instance, owner=None):
new_cls = copy(cls)
new_cls._parent = instance
return new_cls
class OuterClass:
class InnerClass(metaclass=Meta):
def get_parent_link(self):
return self._parent
parent_obj = OuterClass()
child_obj = parent_obj.InnerClass()
child_obj.get_parent_link()
Please, note that this is for demonstration purposes only - it will work exactly as you described, but this design will leak memory due to a new copy of inner_class being created each time.
It can be fixed with a wrapper function holding the reference to the parent inside the metaclass __get__, though.
InnerClasshas no knowledge that its class definition statement was executed within the body of another class definition statement, and it certainly doesn't know that its constructor was accessed off of an instance. There is no reference to retain. Why are you nesting the class definitions to begin with? Just explicily pass the object.