5

I have two constructors in my class:

def __init__(self):
  self(8)

def __init__(self, size):
  self.buffer = [1] * size

Where I want the first constructor to call the second with a default size. Is this achievable in python?

Aly
  • 15,865
  • 47
  • 119
  • 191

4 Answers4

10

You cannot define multiple initializers in Python (as pointed in the comments, __init__ is not really a constructor), but you can define default values, for instance:

def __init__(self, size=8):
  self.buffer = [1] * size

In the above code, a buffer of size 8 is created by default, but if a size parameter is specified, the parameter will be used instead.

For instance, let's suppose that the initializer is inside a class called Example. This call will create a new instance of the class with a buffer of size 8 (the default):

e = Example()

Whereas this call will create a new instance with a buffer of size 10:

e = Example(10)

Alternatively, you could also call the constructor like this:

e = Example(size=10)
Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 1
    `__init__` is not a constructor, but rather an initializer. See [`__init__` as a constructor?](http://stackoverflow.com/questions/6578487/init-as-a-constructor). – Nathan Dec 04 '11 at 17:35
  • Thanks for pointing that out, @Nathan. I've edited my answer accordingly. – Óscar López Dec 04 '11 at 17:41
5

No, you cannot overload methods in Python. In this case, you could just use a default value for the size parameter instead:

def __init__(self, size=8):
  self.buffer = [1] * size
omz
  • 53,243
  • 5
  • 129
  • 141
1

probably not in this way. Python classes use an internal dictionary to store its method and properties, a second method with same name overrides the first one. You could assign a default value to your extra parameter to do this,

def __init__(self, size = 8):
  self.buffer = [1] * size
hago
  • 1,700
  • 2
  • 16
  • 18
0

What you suggest is possible in languages that allow constructor overloading. This is not possible in python. For simple cases, the suggested default parameter is the best way ( __init__(self,size=8)). If you need more complex alternative constructors (imagine reading and parsing parameters from a string or so), you would use classmethods in python:

class thingWithBuffer:
    def __init__(self, buffer_size):
        self.buffer = buffersize
    
    @classmethod
        def create_with_default_buffer(cls):
            return cls(buffer_size=8)

pynative has a nice overview of how to use classmethods

JanD
  • 7,230
  • 3
  • 23
  • 24