A better self

Michael Chermside mcherm at destiny.com
Mon Jul 22 16:55:59 EDT 2002


>> 
>> Many people have suggested doing something like the following (which is
>> reasonable) to eliminate self. from mathematical expressions:
>> 
>>   t, x, y, z=self.t, self.x, self.y, self.z
>>   result=sin(t)*x**y+sqrt(z)  # A pretend formula
> 
> Yes, this was suggested earlier.  I don't consider it a great solution
> to the problem.  [...]  it is rather silly to have
> lines like:
> 
>    t, x, y, z=self.t, self.x, self.y, self.z
> 
> in every one of many member functions, often with the same variables.
> You look at that code, with all those redundant lines of negligible
> content, and it yells out to you:  something is missing here that
> should make this silly copying unnecessary in order to have expressions
> that are easy to read/understand.


I agree. Something is missing here. Your problem is that you really 
aren't dealing with "objects", per se, you have these "formulas" in your 
mind. So why don't we use the closest Python equivalent?


     # WARNING: Untested code below

     def pretendFormula(x,y,z,t):
         return sin(t) * x**y + sqrt(z)

     def MyClass:
         def pretend(self):
             return pretendFormula(self.x, self.y, self.z, self.t)

Notice how this has an additional advantage... it allows you to use 
short, simple names for the variables within the formula (the 
traditional to write formula), while still allowing longer, more 
descriptive names within the object:

     ...
         return pretendFormula( self.position.x,
                                self.position.y,
                                self.position.z,
                                self.time )

And while you're at it, you can give a descriptive name to the formula 
itself.

Can't we get the best of both worlds?

-- Michael Chermside







More information about the Python-list mailing list