I am writing a class to implement an algorithm. This algorithm has three levels of complexity. It makes sense to me to implement the classes like this:
class level0:
def calc_algorithm(self):
# level 0 algorithm
pass
# more level0 stuff
class level1(level0):
def calc_algorithm(self):
# level 1 algorithm
pass
# more level1 stuff
class level2(level1):
def calc_algorithm(self):
# level 2 algorithm
pass
# more level2 stuff
Where I expect that calc_algorithm
will be overridden in each class. Depending on a certain commandline option I want to run either level 0, level 1 or level 2 on the data. This is how I call the algorithm:
for offset in itertools.product(*map(xrange, (dim[0] - 1, dim[1] - 1, dim[2] - 1))):
algorithm(offset).calc_algorithm
Where algorithm
is either level0
, level1
or level2
.
The way I'd do it in other languages is:
for offset in itertools.product(*map(xrange, (dim[0] - 1, dim[1] - 1, dim[2] - 1))):
if (level == 0):
level0(offset).calc_algorithm
else:
if (level == 1):
level1(offset).calc_algorithm
else:
level2(offset).calc_algorithm
Is there a Pythonic way to alias a class to refer to another class, so that I could do:
algorithm = (level == 0) and level0 or (level == 1) and level1 or level2
and then call algorithm
as above?
Just for comparison, in Specman, which is an Aspect Oriented language I could write the class like this:
struct algorithm {
level: uint;
// common stuff for all levels
calc_algorithm() is empty;
when (level == 0) {
calc_algorithm() is only {
// level 0 algorithm
};
};
when (level == 1) {
calc_algorithm() is only {
// level 1 algorithm
};
};
when (level == 1) {
calc_algorithm() is only {
// level 1 algorithm
};
};
};
And then once I set the level
struct member, I can use the rest of the class transparently.