Overloading
Jean-Paul Calderone
exarkun at divmod.com
Fri Dec 9 12:45:32 EST 2005
On Fri, 09 Dec 2005 18:29:12 +0100, Johannes Reichel <reichel.johannes at t-online.de> wrote:
>Hi!
>
>In C++ you can overload functions and constructors. For example if I have a
>class that represents a complex number, than it would be nice if I can
>write two seperate constructors
>
>class Complex:
>
>def __init__(self):
> self.real=0
> self.imag=0
>
>def __init__self(self,r,i):
> self.real=r
> self.imag=i
>
class Complex:
def __init__(self, r=0, i=0):
self.real = r
self.imag = i
>
>How would I do this in python?
>
>And by the way, is it possible to overload operators like +,-,*?
>
>def operator+(self,complex2):
> Complex res
> res.real=self.real+complex2.real
> res.imag=self.imag+complex2.imag
>
> return res
def __add__(self, complex2):
res = Complex(self.real + complex2.real, self.imag + complex2.imag)
return res
Jean-Paul
More information about the Python-list
mailing list