0

I'm writing a game in Python. The player character and enemy characters are instances of Person. Characters can have powers, of class Power. When a character uses a power in combat, the Power object needs to know who owns the power (in order to apply whatever effect the power has). How can I let the Power object know who its Person is?

One obvious solution is to include a creation argument storing a reference to the Person. However, this has several issues; one is that any methods of Power will likely then also need access to that variable, which gets awkward as I'm already passing around a bunch of arguments to every method.

I'd rather have a sort of 'clever' solution that allows an object to look 'up' to see where it is. Is there something like this?

henrebotha
  • 1,244
  • 2
  • 14
  • 36

1 Answers1

2

It is not clear exactly how your objects interact, but here is a minimal example of one option:

def Power():

    def use(self, person):
        # do whatever


def Person():

    def __init__(self, power):
        self.power = power

    def use_power(self):
        self.power.use(self)

This provides an interface to the Power in Person, and passes the Person explicitly to the Power when it is used.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Ok, that's not a way that's occurred to me before. Very simple and clear, but also well-structured. Seems like the way to go... – henrebotha Feb 08 '14 at 22:37