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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.