Accessing parent objects
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sun Mar 25 08:30:44 EDT 2018
On Sun, 25 Mar 2018 05:57:40 -0500, D'Arcy Cain wrote:
> That was my original solution but it seems clumsy.
>
> O2 = O1.C2(O1)
Are you intentionally trying to melt my brain with horribly obfuscated,
meaningless names? If so, you've succeeded admirably millennium hand and
shrimp buggarit.
:-)
> IOW passing the parent object to the child class. It just seems like
> there should be some way to access the parent object in C2.
Of course there's a way, it's just tricky. There's just no *automatic*
way.
Classes are no different to any other object: objects only know what they
hold a reference to, not what holds a reference to them. Given:
class Spam:
eggs = "Wibble"
the class Spam knows about the string "Wibble", but the string has no way
of knowing about Spam. The same applies to nested classes:
class Spam:
class Eggs:
pass
There's no difference here, except that unlike strings, classes can hold
references to other objects. So we can inject a reference to Spam to
Eggs, but unfortunately we can't do from inside Spam, since it doesn't
exist as yet!
class Spam:
class Eggs:
pass
Eggs.owner = Spam # NameError
But we can do it from the outside once the class is built:
Spam.Eggs.owner = Spam
Some possible solutions:
- use a class decorator or a metaclass
- do the injection in the Spam __init__ method:
class Spam:
class Eggs:
pass
def __init__(self):
self.egg = egg = type(self).Eggs()
egg.owner = self
Possibly use a Weak Reference instead of a regular reference.
--
Steve
More information about the Python-list
mailing list