2

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 Answers2

3

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()
Mandera
  • 2,647
  • 3
  • 21
  • 26
  • Thanks a ton!! Does the underscore before "Leg" in the class declaration mean anything syntax-wise? – quantumchocolate Nov 23 '20 at 21:20
  • 1
    Glad I could help! No it's just a [naming convention](https://stackoverflow.com/a/1301369/3936044) for a weak "internal use" indicator – Mandera Nov 24 '20 at 06:19
1

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
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69