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?
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 use
d.