Hi,
I have a conceptual Python design dilemma.
Say I have a City
class, which represents a city in the database. The City
object can be initialized in two ways:
- An integer (actually, an ID of an existing city in a database)
- A list of properties (
name
,country
,population
, ...), which will generate a new city in the database, and retrieve its ID.
This means that the City object will always have an ID - either the initialized ID or a newly-created ID derived from the database.
The classic Java approach would overload the constructor - One constructor would get a single int
parameter, and the other would get numerous strongly-typed parameters.
I've failed to find an elegant way to do it in Python:
- I can create a base class with a single method
get_city_id
, and deriveCityFromID
andCityFromNewData
from it, but that's a lot of effort to work around this language lacuna. - Using class methods seems awkward.
- Using a constructor with a long list of parameters is also awkward: I'd put both city id and the alternatives, and verify within the method that that only a specific subset have values.
Using **kargs
seems very inelegant, because the signature of the constructor does not clearly state the required input parameters, and docstrings just ain't enough:
class City(object):
def __init__(self, city_id=None, *args, **kargs):
try:
if city_id==None:
self.city_id=city_id
else:
self.city_name=kargs['name']
except:
error="A city object must be instanciated with a city id or with"+\
" full city details."
raise NameError(error)
Is there a Pythonic, elegant solution to constructor overloading?
Adam