[Tutor] Dynamic creation of class instances...

Andrei Kulakov ak@silmarill.org
Wed, 22 May 2002 18:04:55 -0400


On Wed, May 22, 2002 at 02:02:00PM +0100, alan.gauld@bt.com wrote:
> >  Right now I start out with a list of names, craft a string that 
> >  looks like a class instantiation and then exec the sucker.  
> 
> Paul has already answered this based on a dictionary solution.
> 
> But this is an issue for everyone on the list.
> 
> Why does this same question come up every month on this list?
> It has to be one of the top FAQs for this mailing list.
> 
> It suggests to me that something in the standard tutorials/texts 
> must be suggesting this solution to people. Its such a bizarre
> solution that it never seems to come up in any of the other 
> fora that I engage with(Delphi, C++, Smalltalk, Java(spit!) ).
> 
> But on Python it seems like most newbies sooner or later come 
> up with this amazing idea for naming objects using exec.
> 
> So Why? Comments welcomed from newbies who've been there, or 
> from newbies whpo nearly went there or from exorerienced hackers 
> who might know why it comes up so often?
> 
> I am seriously puzzled and if I can do anything in my tutor to
> circumvent it(short of discussing it explicitly!) I will.
> 
> Alan g.
>
Tutorials start out with variables and instances defined in the
namespace, as opposed to being in lists or dictionaries.

class Person:
    def __init__(self, name):
        self.name = name

fred = Person("Fred Krabappel")

then it's referenced as fred.name

What if you want the program to get the name from raw_input? You
intuitively long for something like exec that will do exactly the
same operation for the name user entered.

When we're learning something new and complicated, we try to take
smallest possible steps instead of leaping ahead like "Now I will
not only get the name from raw_input but will also store it in a
list instead of a var in namespace like I did before".

The solution is to touch on this topic in tutorials. Yes, exec
seems like a natural here but it's not the best idea because
[...].

> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org