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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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: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):Whereas this call will create a new instance with a buffer of size 10:
Alternatively, you could also call the constructor like this: