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?
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?
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)
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
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
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)