I'm sure there's some programming paradigm to cover this case, but I can't find the correct wording for it, and therefore my Google-fu is worthless.
I have a class called SimpleWorld
that has methods, and inside those methods, the class likes to instantiate objects. Now all of these instantiated objects subclass a particular superclass that gives them a property called world
. However, within my SimpleWorld
, the world is always one particular value.
class WorldBeing:
def __init__(self, world):
self.world = world
class Animal(WorldBeing):
pass
class Player(WorldBeing):
pass
class SimpleWorld:
def __init__(self):
self.world = []
def add_player(self):
self.world.append(Player(self.world))
def add_two_animals(self):
self.world.append(Animal(self.world))
self.world.append(Animal(self.world))
How can I structure this better, so that the self.world
doesn't have to keep on being repeated for all of these animals and players?
In fact, for each WorldBeing
within SimpleWorld
, that being's world will always be the world of the simple world. So if I were to create another type class Plant(WorldBeing)
, whenever SimpleWorld
instantiated a plant, that plant would also always take the same world
parameter in order to be instantiated.
Can this issue be solved with a particular programming paradigm? If so, what is that paradigm called, and how would I implement it in Python?
If there's no particular paradigm, what would be the best way to simplify the SimpleWorld
into not always needing to specify that parameter for each new object?
(Ideally, I'd like to assume that we can only edit SimpleWorld
, but I'm willing to accept changes to the other classes as well if it really helps the structure.)
What I've considered so far:
I've considered trying to define new classes inside SimpleWorld
(such as SimpleWorldAnimal
), but it seems tedious to create a new internal class for each external one (and it's also difficult to define new classes that use SimpleWorld
's self.world
in their __init__
and still have them defined outside SimpleWorld
's __init__
). I'm really hoping that's not the best solution.
I've also looked into dynamic classes, but I can't think of a good way of using them yet.
Multiverse
class where WorldBeing's exist in different worlds?say_hello_to_random_player
method, which searches the world for a different player to say hello to. So generally the instances need to know what world they're in because they have actions they perform based on the other instances in that same world.