[Tutor] Object Instantiation via Dictionary Values
Jeff Shannon
jeff@ccvcorp.com
Fri Feb 28 21:08:03 2003
Sean Abrahams wrote:
>I want to create new objects with names and classes that are stored
>inside a list of dictionaries.
>
>Example:
>
>modules = [{'Name' : 'Sean', 'Type' : 'Person'},
>{'Name' : 'Buddy', 'Type' : 'Dog'},
>{'Name' : 'Evil', ' Type' : 'Cat'}]
>
>for module in modules:
> module['Name'] = module['Type'].module['Type']()
> # Would be:
> # Sean = Person.Person()
> # Buddy = Dog.Dog()
> # Evil = Cat.Cat()
>
>
>I'm not exactly sure how to go about this, but assume it has something
>to do with using special methods.
>
Not if you're happy keeping your created objects in a dictionary. I
presume that you have, say, a module Person.py that contains class
Person, etc? If you've already imported your modules, they'll be in
sys.modules; if not, you can investigate the imp() builtin (IIRC).
Presuming you've already imported them, and also sys:
objects = {}
for module in modules:
type = module['Type']
mod = sys.modules[type]
objects[module['Name']] = getattr(mod, type)()
This is completely untested, and just off the top of my head, so use
with caution -- but I think it should work, or at least give you a
general idea...
Jeff Shannon
Technician/Programmer
Credit International