class Parent():
def __init__(self):
self.child = Child()
class Child():
def __init__(self):
# get Parent instance
self.parent = self.Instantiator()
I know this isn’t proper encapsulation but for interest’s sake…
Given a “Parent” class that instantiates a “Child” object, is it possible from within Child to return the Parent object that instantiated it? And if no, I’m curious, do any languages support this?
Here’s a reasonably-simple metaclass solution to the problem:
a typical output, depending on the platform, will be something like
You could obtain a similar effect (in 2.6 and later) with a class decorator, but then all classes needing the functionality (both parent and children ones) would have to be explicitly decorated — here, they just need to have the same metaclass, which may be less intrusive thanks to the “module-global
__metaclass__setting” idiom (and the fact that metaclasses, differently from class-decorations, also get inherited).In fact, this is simple enough that I would consider allowing it in production code, if the need for that magical “instantiator” method had a proven business basis (I would never allow, in production code, a hack based on walking the stack frames!-). (BTW, the “allowing” part comes from the best-practice of mandatory code reviews: code changes don’t get into the trunk of the codebase without consensus from reviewers — this how typical open source projects work, and also how we always operate at my employer).