1

I am trying to build a complex number calculator in python. The number will be represented by a class with two fields. The first constructor I want to use looks like this:

def __init__(self,real,imag):
    self.real = real
    self.imag = imag

but i would like to use another, where the only parameter will be a string representing the whole number:

def __init__(self,string_number):

How to implement the overload that allows to use different number of parameters? I am more used to C++, where such thing was easy. Thanks a lot!

EDIT: Question marked as duplicate: I did not find any answer regarding different number of parameters. The error I get when trying to build a new instance of the class is about to few arguments.

Luke
  • 11
  • 3
  • You want both the constructors to be of same class? – Sushant Jul 25 '18 at 09:28
  • Yes. I typed the second constructor in as an example (it is not in the definition of the class). Tried to use @classmethod but i get the error of to few arguments when using the second one. – Luke Jul 25 '18 at 09:35
  • Yes, you can't use multiple constructors in python. Look at the answers above – Sushant Jul 25 '18 at 09:36
  • 1
    The question is a duplicate! `def __init__(self, real, imag): ...` and `@classmethod def from_string(cls, string): r, i = string.split(); return cls(int(r), int(i.replace('j', '')))` or something like that. Then you'd either do `Complex(real, imag)` or `Complex.from_string(string)`. – FHTMitchell Jul 25 '18 at 09:42
  • Ok, it turned out to be simpler than expexted. I just used def __init__(self,first,second = None) and then if isinstance(first, str) and isinstance (first, int) Thanks guys! – Luke Aug 08 '18 at 10:29

0 Answers0