A slight variant is to dispatch on the init:
class MyThing(object):
def __init__(self, **kwarg):
s = kwarg['source']:
if s == 'db':
self._init_db(**kwarg)
elif s == 'json':
self._init_sson(**kwarg)
else:
raise ValueError("invalid source")
def _init_db(self, **kwarg):
pass
def _init_json(self, *
Thanks - you're right, I do see this often. I did something similar at
first. I changed to performing it in the __init__ function since:
1) I can group similar init code as I develop it
2) I have multiple database and front-end sources that might create an
Event object, so I might end up with awk
A common pattern is class methods as constructors:
class MyThing(object):
@classmethod
def from_db(cls, row):
obj = cls()
... # initialize attributes from database row
return obj
@classmethod
def from_json(cls, data):
obj = cls()
... # init
I have an Event class that creates an object when "events" are pulled from
the database. It also creates event objects from user input - the user can
then commit() these events to the database.
So, event objects are created from two different sources (actually more,
but, for simplicity..): fro