[Tutor] Problem on select esecution of object in a class

Alan Gauld alan.gauld at btinternet.com
Wed Aug 5 18:55:45 CEST 2015

On 05/08/15 17:04, jarod_v6--- via Tutor wrote:

>          for i in "ena."+"".join(diz[id])+"()":
>              print i.command

Here you are creating a string and then iterating over
the string one character at a time. But the characters
do not have a command attribute.

> ----> 3                 print i.command
>        4
> AttributeError: 'str' object has no attribute 'command'

As shown by the error message.

> here you se what they ouptut
> "ena."+"".join(diz[id])+"()"
> Out[85]: 'ena.trimmomatic()
> Definition: ena.trimmomatic(self)

These are not the same thing at all. The second is the
description of a method of your class not a string.
The fact that the name of the method happens to be
the same as the string contents makes no difference
to Python.

> Any suggestion in how to choose the function to use?

The usual way to translate a string to a function is to
use a dictionary with name: function pairs.

But your class already builds one of those so you can use
the getattr() function to get the attribute:

myMethod = getattr(myobj, attr_name)


myResult = getattr(myobj, attrName)(params)

to call the method.

However, building function names as strings and then calling
them is usually a bad design pattern. Especially for large
numbers of objects. So maybe if you explain what/why you are
doing this we can suggest a better alternative.

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list