The inner class does not offer special features in Python. This is only a property of a class object, other than integer or string. Your OuterClass / InnerClass example can be rewritten in the same way:
class OuterClass(): pass class InnerClass(): pass OuterClass.InnerClass= InnerClass
InnerClass cannot know if it was declared inside another class, because it is just a variable binding. The magic that makes related methods know about its owner is not applied here.
The way the decorator of the inner class in the link posted by John is an interesting approach, but I would not use it as it is. It does not cache the classes that it creates for each external object, so every time you call externalinstance, you get a new InnerClass. InnerClass:
>>> o= OuterClass() >>> i= o.InnerClass() >>> isinstance(i, o.InnerClass) False
Also the way he tries to replicate Java behavior by making class external variables available in the inner class using getattr / setattr is very dodgy and unnecessary (since the more Pythonic path would have to call i .__ external __. Attr explicitly) .
bobince
source share