Method default argument whose type is the class not yet defined

Oscar Benjamin oscar.j.benjamin at gmail.com
Sun Nov 11 02:23:08 CET 2012


On 10 November 2012 19:33, Jennie <nameDOTportua at gmail.com> wrote:
> What is the best solution to solve the following problem in Python 3.3?
>
> import math
>>>> 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=Point()):
> ...         """Return the distance from `point`."""
> ...         return math.sqrt((self - point).x ** 2 + (self - point).y ** 2)
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 5, in Point
> NameError: name 'Point' is not defined

I would use namedtuple and make it so that an ordinary tuple could be
used as in place of a Point instance:

>>> import math
>>> from collections import namedtuple
>>> class Point(namedtuple('Point', ['x', 'y'])):
...   def distance(self, other=(0, 0)):
...     (myx, myy), (theirx, theiry) = self, other
...     return math.sqrt((myx - theirx) ** 2 + (myy - theiry) ** 2)
...
>>> p = Point(3, 4)
>>> p.distance()
5.0
>>> p2 = Point(4, 5)
>>> p.distance(p2)
1.4142135623730951


Oscar



More information about the Python-list mailing list