[Tutor] How to use a str object, to find the class in exact name?

Steven D'Aprano steve at pearwood.info
Mon Mar 14 23:14:09 CET 2011


Yaşar Arabacı wrote:
> Hi
> 
> I am trying to do something like this:


If you are trying to write a mini-language, the ``cmd`` and ``shlex`` 
modules in the standard library may be useful to you.


> #!/usr/bin/env python
> def command_dispatcher():
>     "Takes comman line arguments and executes regardin method"
>     command = raw_input(">>>")
>     args = command.split(" ")
>     args[0].args[1]


The error you get tells you exactly what is wrong:

AttributeError: 'str' object has no attribute 'args'


When you split the line, you get a list of strings. You extract the 
first string using args[0], and then look up the attribute "args" on 
that string, and finally look up the second element of that result. But 
strings don't have an attribute called args.

Try this instead:

getattr(args[0], args[1])

When you do that, you'll run into a bunch of new and exciting errors, 
starting with the fact that nothing appears to happen. Try it and see.

What you will eventually need to do is:

* create a class instance and store it somewhere
* call the method on the class instance
* print its output

none of which is yet done by your script. So far, all it does it try to 
look up a method on a class, then throw the result away without doing 
anything :)


> class calculate:
>     def bundle(self):
>         print __class__
> command_dispatcher()


calculate.bundle won't do anything except fail, because __class__ is not 
a local variable.

It's better to have the methods return a result, rather than print, and 
then have the command_dispatcher responsible for printing it. That lets 
you chain methods to make more powerful functions.


Good luck, and have fun!



-- 
Steven



More information about the Tutor mailing list