0

I have two constructors in one class, but when I call one of them (a one with one argument - only self - instead of a one with 4 arguments), it results in an error, saying it expected more arguments than the 1 given.

The class is the following way:

class Message:
def __init__(self):
    self.data = None

def __init__(self, type, length, data):
    self.type = type
    self.length = length
    self.data = data

and the call to it (where I also get the error is at):

msg = Message()

Where might be the problem? Isn't it comparable to C++? If not, how can I still get the same result in another way?

Meno
  • 3
  • 1
  • 4
    Python doesn't allow this behaviour - the second `__init__` **completely replaces** the first one. *"Isn't it comparable to C++?"* - only insofar as you can say it's not like C++! – jonrsharpe May 12 '15 at 15:25
  • Technically, `__init__` is not a constructor, but an initializer. It receives an already-constructed object as an argument. `__new__` is the constructor. – chepner May 12 '15 at 15:38

2 Answers2

1

You cannot have two __init__ methods in a single class.

What your code effectively does is override the first method so it is never used, then you get an error because you haven't supplied enough arguments.

One way to get around this would be to supply default values using keyword-arguments. In this way if you create the Message object with no values, it'll use the defaults. The example below uses None as the default value but it could be something more complex:

class Message(object):

    def __init__(self, type=None, length=None, data=None):
        self.type = type
        self.length = length
        self.data = data
Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
0

Python doesn't work that way. Use this:

class Message:
    def __init__(self, type=None, length=None, data=None):
        self.type = type
        self.length = length
        self.data = data
paidhima
  • 2,312
  • 16
  • 13