If I have an object that is a property of another object, how can I reference the main object from the property object?

Viewed 45

Apologies if title was a little unclear. A little shaky on Python object-oriented fundamentals, but here is a basic example: Let's say I have a "Body" class and a "Legs" class, and I have an instance of "Legs" (rightLeg) as a property of a "Body" instance (georgesBody). If I call a function like rightLeg.break(), how can I, inside of break() for the "Legs" class, ping the corresponding "Body" instance and pass it some information (maybe through a setter method of "Body" set up to accept said ping)?

I need to be able to trigger code that calls the specific instance of "Body", georgesBody, from within rightLeg dynamically (without referencing the actual name georgesBody). Any help is much appreciated!

2 Answers

I would define the legs inside the __init__ method of Body, then link them to eachother by requiring a body argument for the legs.

class Body:
    def __init__(self):
        self.left_leg = _Leg(self)
        self.right_leg = _Leg(self)

class _Leg:
    def __init__(self, body):
        self.body = body

    def break_leg(self):
        print(self, self.body)

Body().left_leg.break_leg()

What you want to do could be done by a publish/subscribe mechanism with messages

Simpler is to provide the body upon instantiating the legs - but that way you also have tighter coupling and legs need to know about the bodys methods it can call:

class Leg: 
    def __init__(self, side, body): 
        self.side = side
        self.body = body

    def destroy(self):
        # call something on the body
        self.body.shout("Leg broken: " + self.side)

class Body: 
    def __init__(self): 
        self.legs=[Leg("left", self), Leg("right", self)]
    def shout(self, msg):
        print(msg)


b = Body()
b.legs[0].destroy()
b.legs[1].destroy()

Output:

Leg broken: left
Leg broken: right
Related