I have a Maze class, and I have a MazeTilePlacer (MTP) class. The MTP class instances will be created inside the Maze class, and need access to a variable named emptytiles in the maze class, defined as self.emptytiles = []
. How can I access the parent object from the MTP instance to access this variable?
CodePudding user response:
You can handle this by giving each instance of MazeTilePlacer
a reference to the same emptytiles
list as your Maze
object has. The Maze
object can then delegate the responsibility of placing tiles to the other objects.
class Maze:
def __init__(self):
self.emptytiles = []
def place_tiles(self):
placer = MazeTilePlacer(emptytiles=self.emptytiles)
placer.do_placements()
class MazeTilePlacer:
def __init__(self, emptytiles):
self.emptytiles = emptytiles
def do_placements(self):
self.emptytiles.append('Another tile my Sir')
maze = Maze()
maze.place_tiles()
print(maze.emptytiles)
If you want to have multiple tile placers, you can all give them the same reference for emptytiles. If you need these to run in parallel and manipulate the emptytiles structure in a thread safe manner (i.e. where you need to have multiple accesses without anyone changing the structure under you - for example pop, do something, then append without something being popped or appended in between) you'll have to wrap it in a lock.