Method default argument whose type is the class not yet defined
Jennie
marco.buttu at gmail.com
Sat Nov 10 21:51:38 CET 2012
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 :)
--
Jennie
More information about the Python-list
mailing list