Multiple constructors in python?

Chris picture Chris · Jan 29, 2010 · Viewed 264.4k times · Source

Possible Duplicate:
What is a clean, pythonic way to have multiple constructors in Python?

Is it not possible to define multiple constructors in Python, with different signatures? If not, what's the general way of getting around it?

For example, let's say you wanted to define a class City

I'd like to be able to say someCity = City() or someCity = City("Berlin"), where the first just gives a default name value, and the second defines it.

Answer

Andrew Sledge picture Andrew Sledge · Jan 29, 2010

Unlike Java, you cannot define multiple constructors. However, you can define a default value if one is not passed.

def __init__(self, city="Berlin"):
  self.city = city