[Tutor] instantiating subclass by parameter
Lloyd Kvam
pythontutor at venix.com
Tue Oct 28 19:28:40 EST 2003
Well, normally you would have your code organized so that there
was an object - other than the module namespace - to hold the names.
There is a function, globals() which provides the dictionary used
for managing the names in the module namespace. I believe that it
is usually possible to assign values into that dictionary. However,
the need to do that is an indication that you are using Python to
code some other language.
In other words, if you want to be able to write
alpha.foo()
then why are you relunctant to write
alpha = factory('altavista')
If you need to setup some other class to be able to use alpha as a
variable name, then you can use the setattr function on that object
to create the variable alpha initalized to the proper instance of
WebSearch.
I think if you simply do direct assignments for now, as your code evolves,
you'll find a resonable object or container to hold the WebSearch
instances.
I hope that helps.
Karl Fast wrote:
>>Here you need something to hold the objects that you are creating.
>> create = {'alpha': 'altavista', 'beta': 'alltheweb'}
>> for key in create:
>> key = factory(create[key])
>
>
> I understand what's going wrong here. I knew it wasn't working and I
> knew why, but thanks for your explanation which confirms it.
>
>
>
>>The folowing code where you use a dictionary named obj to hold the
>>objects with the specified key names (alpha, beta) looks like it
>>should work.
>
>
> Yes, it does work (tested it before posting).
>
> I'm just wondering if there is another way of doing this that would
> give me objects based on the name in the dict, instead of a dict
> holding the objects where the objects are accessible by key.
>
> That is, instead of accessing the results like this:
>
> obj['alpha'].foo()
> obj['beta'].name
>
> I could access them like this:
>
> alpha.foo()
> beta.name()
>
> The dict solution works. As an exercise in learning python I'm
> wondering if is another solution that would give me the second
> result.
>
> In other words, is there a way to change the line that calls factory
> so that it creates the objects alpha and beta.
>
> create = {'alpha': 'altavista', 'beta': 'alltheweb'}
> for key in create:
> key = factory(create[key])
>
> alpha.foo()
>
>
> --karl
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice: 603-653-8139
fax: 801-459-9582
More information about the Tutor
mailing list