Hiya,
This is really more a general programming question than a python-in-edu
question, but it's related to project for education that I'm working on,
and based on lurking for a while I'm pretty sure some members of the
list will have some interest and expertise to answer.
Say I have some class definitions like this:
class Expression:
stuff
class LinearExpression(Expression):
stuff
class QuadraticExpression(Expression):
stuff
Is there any way to make the Expression constructor return an instance
of one of the subclasses (based on its arguments) rather than an
Expression instance. E.G.
e=Expression("3x+5")
e.__class__ == <class LinearExpression>
e=Expression("x^2-9")
e.__class__ == <class QuadraticExpression>
I can think of plenty of workarounds involving helper functions and I
can think of a number reason why idiom given above might not be The
Right Thing whether or not it is possible. But I can't help thinking
that there is an elegance to this approach: Let the superclass choose
the appropiate subclass as an implementation, based on what it is
supposed to represent.
Similarly, can a class constructor choose not to construct a class and
instead return a base type object? For example (assuming Fraction is a
suitably designed class for rationals), can you do:
f=Fraction(1,2) # Fraction(n,d) => n/d
type(f) == <type 'instance'>
f=Fraction(2,1)
type(f) == <type 'int'>
Again, I can think of reasons not to do this, but it seems reasonable to
let the class pick the most appropriate implementation of itself as
possible, and if that is a builtin type, why not?
It's probably obvious from my examples that I'm interested in computer
algebra. I've found a few python CA systems: fewer than I'd expect,
more than I'd like to evaluate one by one, none well documented enough
for me to guess how easy to use/featureful they are. Anybody got any
advice/pointers for good, extensible computer algebra implementations
under python?
Thanks,
Jay