Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor chaining in python

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?

like image 651
Aly Avatar asked Dec 04 '11 16:12

Aly


2 Answers

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)
like image 193
Óscar López Avatar answered Oct 11 '22 13:10

Óscar López


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
like image 26
omz Avatar answered Oct 11 '22 14:10

omz