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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With