how to use more than 1 __init__ constructor in a class ?

F. Petitjean littlejohn.75 at news.free.fr
Wed Jun 22 21:08:25 CEST 2005


Le 22 Jun 2005 11:44:09 -0700, wittempj at hotmail.com a écrit :
> You also could use a list to represent your data, then you get more
> dimensions supported, e.g:
> import math
> class Point:
> 	def __init__(self, *args):
> 		self.points = list(args)
>
> def dist(x, y):
> 	if len(x.points) != len(y.points):
> 		raise RuntimeError('dimensions not the same')
> 	d = 0
> 	for i in range(len(x.points)):
> 		d += (x.points[i] - y.points[i])**2
> 	return math.sqrt(d)
>

My rewrite (same idea) :-)
class Point(object):
    def __init__(self, *args):
        self.coords = list(args)  # or even args ?

    def dist(self, other):
        d2 = sum([ (c1-c2)*(c1-c2) for c1, c2 in zip(self.coords,
            other.coords)])
        return math.sqrt(d2)





More information about the Python-list mailing list