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?

1
  • 4
    You don't have two constructors, the second overwrites the first. Commented Dec 4, 2011 at 16:43

4 Answers 4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

__init__ is not a constructor, but rather an initializer. See __init__ as a constructor?.
Thanks for pointing that out, @Nathan. I've edited my answer accordingly.
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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.