Method default argument whose type is the class not yet defined

Dave Angel d at davea.name
Sat Nov 10 23:30:14 CET 2012


On 11/10/2012 03:51 PM, Jennie wrote:
> On 11/10/2012 09:29 PM, Terry Reedy wrote:
>
>> On 11/10/2012 2:33 PM, Jennie wrote:
>>>
>>> I propose three solutions. The first one:
>>>
>>>  >>> class Point:
>>> ...     def __init__(self, x=0, y=0):
>>> ...         self.x = x
>>> ...         self.y = y
>>> ...     def __sub__(self, other):
>>> ...         return Point(self.x - other.x, self.y - other.y)
>>> ...     def distance(self, point=None):
>>> ...         p = point if point else Point()
>>> ...         return math.sqrt((self - p).x ** 2 + (self - p).y ** 2)
>
>> What I do not like about this one is that it creates a new 0 point each
>> time one is needed. Two solutions:
>>
>> change Point() to point0 in the distance function and create
>> point0 = Point()
>> after the class.
>>
>> -or-
>> instead of p = line,
>> px,py = point.x, point.y if point else 0.0, 0.0
>
> Thanks, I like the second one :)
>
I like the first, once you fix the minor inefficiency in it;  add the
qualifier "is None"


...     def distance(self, point=None):
...         p = point if point is None else Point()
...         return math.sqrt((self - p).x ** 2 + (self - p).y ** 2)

The advantage it then has over the second one is that the whole class is
defined inside the class.

-- 

DaveA




More information about the Python-list mailing list