OO design question / Transform object in place?

andy2O at hotmail.com andy2O at hotmail.com
Fri May 20 06:43:35 EDT 2005


Dave Benjamin wrote:
> andy2O at hotmail.com wrote:
> > Now suppose I set "expression2 = Sum([a,-a])" and Sum.simplify()
> > recognises that the two terms cancel and the Sum has value 0.
> >
> > Can I make "expression2.simplify()" transform expression2 from an
> > instance of Sum to an instance of Number(0) **in place**? Is that
> > possibe, or do I really have to write
>
> I think it's much better for simplify() to return a new object
always,
> and leave the original object unmodified. You can still write:
>
> expression2 = expression2.simplify()

Dave,

A belated thank-you message for your reply to my posting. I took your
advice, and made all the simplify methods return new objects and this
has simplified my code structure a great deal (and any slow down in run
time just doesn't matter!).

Am I right that to make "expression2.simplify()" return a new object I
will need use copy.copy a lot, as in:

def simplify(self):
    newreturnvalue=copy.copy(self)
    #
    #....now the code does lots of complicated things
    #    to newreturnvalue object...
    #
    return newreturnvalue

I have a nagging doubt as to whether this is what you meant, or if I've
missed a trick again.

Anyway, thanks again for your reply.

Yours,
Andy.

>
> if you don't care about the old value.
>
> > expression2 = SimplifyFunction(expression2)
>
> This is another valid solution, but it's not an OO solution (you will

> need to use "isinstance" to write "SimplifyFunction").
>
> > and use the function return to set expression2 to be a Number(0)
> > object, which is annoying for a variety of reasons! Have I made a
> > mistake in the design?
>
> It's usually considered poor OO style to have an object change its
class
> at runtime, although I'm sure you could do it in Python ("__bases__"
> would be a place to start) if you really wanted. For what you're
trying 
> to do, I don't think it's necessary, though.
> 
> Dave




More information about the Python-list mailing list