to setattr or def setProp()

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Tue Nov 14 08:26:29 CET 2006


On Mon, 13 Nov 2006 22:20:03 -0800, jm.suresh at no.spam.gmail.com wrote:

> I have a class for rectangle and it has two points in its __slots__ .
> However, we can derive a number of properties like width, height,
> centerPoint etc from these two points. Now, I want to be able to set
> and get these properties directly from the instances. I can either def
> __setattr__ , __getattr__  or I can define function for each property
> like setWidth(), setHeight() . Which one would be faster? I would
> prefer doing through __setattr__, __getattr__ because it makes the code
> more readable.
> However, speed is a concern I would have to do these operations in few
> thousand iterations for about 50-100 rectangles.

>>> class Rect(object):
...     def __init__(self, a,b,c,d):
...             # too lazy to use slots, sorry
...             self.a, self.b, self.c, self.d = a, b, c, d
...     def _width(self):
...             return self.c - self.a
...     width = property(_width, None, None, None)
...
>>>
>>> r = Rect(1, 2, 3, 4)
>>> r.width
2

Now let's see how fast it runs.

>>> import timeit
>>> timeit.Timer("r.width", "from __main__ import Rect; r = Rect(1,2,3,4)").timeit()
2.3775210380554199

Now you know how to test how fast code runs, you can write some code to
test.


-- 
Steven D'Aprano 




More information about the Python-list mailing list