[Python-ideas] Mitigating 'self.' Method Pollution
Terry Reedy
tjreedy at udel.edu
Sun Jul 12 03:21:57 CEST 2015
On 7/11/2015 3:41 PM, David Mertz wrote:
> On Sat, Jul 11, 2015 at 12:10 PM, Nikolaus Rath
> <Nikolaus at rath.org
> <mailto:Nikolaus at rath.org>> wrote:
>
> > class Vector:
> > def abs(self):
> > return sqrt(x**2 + y**2 + z**2)
> > # versus
> > return sqrt(self.x**2 + self.y**2 + self.z**2)
or
def abs(v):
return sqrt(v.x**2 + v.y**2 + v.z**2)
> But I also don't want to have to guess about WHICH 'x' or 'y' or 'z' is
> the one being used in calculation of Cartesian distance. Sure, an
> obvious implementation of a Vector class probably has x, y, z attributes
> of self. The example was rigged to make that seem obvious. But even
> then, I don't really know. Maybe the z direction of the vector is
> stored as a class attribute. Maybe the class expects to find a global
> definition of the z direction.
>
> Sure, keeping the z direction somewhere other than in self is probably
> foolish if you assume "Vector" means "generic vector". What if the
> class was called "RestrictedVector"? Would you know without reading the
> full class and docstring exactly in what respect it is "restricted"?
> E.g. are you sure it's not "restricted in the z dimension"?
>
> As someone else points out, if you WANT local variables in a method, you
> are welcome to use them. E.g.:
>
> def times_matrix(self, matrix):
> x, y, z = self.x, self.y, self.z
> # Many more than one line of implementation
> # ... stuff with matrix indexing and referencing x
> # etc.
> return result_matrix
Localization, which is not limited to self attributes, does two things:
it removes the need to continually type 'object.x'; it makes the
remaining code run faster. I would be interested to know how many
faster local references are needed to make up for the overhead of
localization.
--
Terry Jan Reedy
More information about the Python-ideas
mailing list