Method default argument whose type is the class not yet defined

Chris Angelico rosuav at
Sat Nov 10 20:56:17 CET 2012

On Sun, Nov 11, 2012 at 6:33 AM, Jennie <nameDOTportua at> wrote:
> ...     def distance(self, point=None):
> ...         p = point if point else Point()

I'd go with this one. Definitely not the third one, which mutates the
class according to a current global every time a Point is instantiated
- could be *extremely* confusing if the name distance were ever
rebound. You could also fiddle with the default args:

>>> 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 math.sqrt((self - p).x ** 2 + (self - p).y ** 2)

>>> Point.distance.__defaults__=Point(), # has to be a tuple


More information about the Python-list mailing list