Is there any easy to get a new class based on an old class which is just set some default arguments value of the old class? Code like this:
class DB():
def __init__(self, ip, port, dbname, table):
self.ip = ip
self.port = port
self.dbname = dbname
self.table = table
def process(self):
print self.ip, self.port, self.dbname, self.table
Now I need to get a set of new classes with some default values of OldClass.a, OldClass.b, OldClass.c, I will do like below:
class UserDB(DB):
def __init__(self, dbname, table):
OldClass.__init__(self, ip='user.db.com', port='1234', dbname=dbname, table=table)
class ProdDB(DB):
def __init__(self, dbname, table):
OldClass.__init__(self, ip='prod.db.com', port='1314', dbname=dbname, table=table)
class CommentDB(DB):
def __init__(self, dbname, table):
OldClass.__init__(self, ip='comment.db.com', port='1024', dbname=dbname, table=table)
class MeetingDB(DB):
def __init__(self, dbname, table):
OldClass.__init__(self, ip='meeting.db.com', port='8888', dbname=dbname, table=table)
userDB = UserDB('user', 'new')
userDB.process()
prodDB = ProdDB('prod', 'lala')
prodDB.process()
commentDB = UserDB('comm', 'gg')
commentDB.process()
meetingDB = MeetingDB('met', 'ok')
meetingDB.process()
I remember there are some tricks to simplify these child class verbosity codes. Any advice is welcome. Thanks in advance.
NewClass3andNewClass4, right? Furthermore: which verbosity do you want to remove? Do you want to automatize the change of the digit at the end of each argument, depending on the Class name?NewClass1. Also, redefiningNewClass1three times does not make any sense because only the last definition will be available.functools.partial, perhaps. If you do need classes, what you have is probably about as good as you can get.