OO design question / Transform object in place?

Dave Benjamin ramen at lackingtalent.com
Fri May 20 13:43:38 EDT 2005


andy2O at hotmail.com wrote:
> Dave Benjamin wrote:
> 
>>I think it's much better for simplify() to return a new object
>>and leave the original object unmodified. You can still write:
>>expression2 = expression2.simplify()
> 
> 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!).

No problem. Glad it helped. =)

> 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

You could use copy.copy(), as long as you want a shallow copy and you 
don't want to change from one class to another. However, it may be to 
your advantage to use the constructor of one or more classes to build 
the result; this allows you to conditionally pick the result object's 
class. Also, there may be situations where an object can't be 
simplified, in which case you can just return "self", and avoid copying 
entirely.

Dave



More information about the Python-list mailing list