the annoying, verbose self

greg greg at cosc.canterbury.ac.nz
Fri Nov 23 20:22:27 EST 2007


BJörn Lindqvist wrote:

> 6        def abs(self):
> 7            return math.sqrt(self.x * self.x + self.y * self.y +
> self.z * self.z)

I would write that as

    def abs(self):
       x = self.x
       y = self.y
       z = self.z
       return math.sqrt(x * x + y * y + z * z)

Not only is it easier to read, it's also more efficient,
because it avoids looking up instance variables more than
once.

--
Greg



More information about the Python-list mailing list