Constructor chain 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 the default size. Is this possible in python?

+5
source share
3 answers

You cannot define multiple initializers in Python (as indicated in the comments, is __init__ not a constructor ), but you can define default values, for example

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.

, , Example. 8 ( ):

e = Example()

10:

e = Example(10)

:

e = Example(size=10)
+9

, Python. size:

def __init__(self, size=8):
  self.buffer = [1] * size
+5

probably not that way. Python classes use an internal dictionary to store its method and properties, the second method with the same name overrides the first. To do this, you can assign a default value for your optional parameter,

def __init__(self, size = 8):
  self.buffer = [1] * size
+1
source

All Articles