[Tutor] creating an object instance w/out hard-coding the name

Magnus Lycka magnus@thinkware.se
Fri, 18 Oct 2002 14:42:24 +0200


At 08:09 2002-10-18 -0400, dlphone@bellsouth.net wrote:
>Thank you, Magnus. If I understand you, you suggest that I create a=20
>dictionary key from the user input, and that key becomes a reference to a=
=20
>new project object instance.

Yes, don't you think that's a good solution?

Imagine that you could magically introduce
a new variable in the code (which you actually
can, but never mind that now).

You let the user call his project, and
like magic, the next line of code will
reflect his chosen name. So, if he chose
the name "xfiles", it would be:

xfiles =3D Project()

Now what? Everywhere in the program you want
to do anything with the project, it should say
xfiles.report() or xfiles.members.add() or
whatever. If he had called it something else,
your code should say something else. And what
if there are several projects. What should it
say in the code where you do things with
projects?

If you still want to try this, be my guest.

projName =3D raw_input('Project name please: ')
exec(projName + ' =3D Project()')

I don't think it will make you happy...

Besides, there are a lot of restrictions on
variable names that you don't want in project
names. Projects couldn't be called "C++", "42nd
street", "if" or "X-files" for instance.

And what if he would give his project a name you
already use as a variable name. Imagine this:

print "Enter projects, end by pressing only Enter"

while 1:
     projName =3D raw_input('Project name please: ')
     if projName =3D '': break
     exec('%s =3D Project()' % projName)

What will happen if the first project name entered
is "Project"?

You will for quite natural reasons get something like
this when the *second* project name has been entered:

Traceback (most recent call last):
   ...
AttributeError: Project instance has no __call__ method

Well, unless you have a call method in the Project
class, but then you've done something quite different
than could be expected.


--=20
Magnus Lyck=E5, Thinkware AB
=C4lvans v=E4g 99, SE-907 50 UME=C5
tel: 070-582 80 65, fax: 070-612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se