[Tutor] Simulating case statement
Jan Eden
lists at janeden.org
Tue Sep 27 12:02:31 CEST 2005
Hi,
I used to use an extended if...elif sequence to instantiate an object and call this object's display method afterwards:
####
if safe['type'] == pages:
page = Show.Page(id=safe['id'], start=safe['start'] ...),
elif safe['type'] == pages:
author = Show.Author(id=safe['id']...)
...
page.Display()
####
To improve readability, I changed this code to use a dictionary:
####
valid_types = dict(
pages=Show.Page,
authors=Show.Author,
...
)
page = valid_types[safe_parameters['type']](safe_parameters)
page.Display()
####
The problem is that the __init__ methods of the respective classes take a different number of parameters - this is why I pass the whole safe_parameters dictionary.
This has a number of drawbacks when instantiating an object in other situations because I cannot use a default for some parameters while passing some others.
So I'd like to do pass the parameters individually, based on the class. I know I would need to expand the valid_types dictionary to include the parameters - but how can I pass these one by one?
What I came up with is a monster (which does not work anyway):
valid_types = dict(
pages=dict(klasse=Show.Page, parameters=dict(id=safe['id'], start=safe['start'] ...))
authors=dict(klasse=Show.Author, ...)
...
)
page = valid_types[safe_parameters['type']]['klasse'](valid_types['parameters'])
page.Display()
How can I circumvent the if...elif sequence and have the parameters passed individually at the same time?
Thanks for any suggestions,
Jan
--
Common sense is what tells you that the world is flat.
More information about the Tutor
mailing list