I want to define a subclass of a class, and I need it to be upgraded to in one of the class' methods, rather than initialized from the very beginning.
The example is a hobby project with Grids and the distances in them.
So I start a Grid class like this:
class Grid:
def __init__(self):
# A grid is a list of lists of cells.
self.grid = self.prepare_grid()
self.configure_cells()
self.maze = None
def __getitem__(self, a_tuple):
x, y = a_tuple
return self.grid[x][y]
def prepare_grid(self):
...
def configure_cells(self):
...
Then I want to add Distance functionality. I was thinking like in a game where you've improved to became a Distance Grid, with methods like:
class DistanceGrid(Grid):
def set_distances(self, root_cell):
...
def path_to(self, goal):
...
Here comes the tricky part. Since I don't want it to be initialized, but rather improved to, I need a method on the parent class to make it a subclass (looks almost recursive, but hopefully it isn't).
from distances import DistanceGrid
class Grid:
...
def upgrade_distance(self, root):
self = type(self, DistanceGrid)
self.set_distances(root)
Can this be done? I'll keep trying. Thanks
Grid. Why is it not aDistanceGridin the first place if you want to do that?