Discussion:
[Tutor] Problem on select esecution of object in a class
Alan Gauld
2015-08-05 16:55:45 UTC
Permalink
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)

or

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
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Peter Otten
2015-08-05 17:01:31 UTC
Permalink
I have a class with many objects and I want to select using opt parse
some function id = options.step
ena = Rnaseq(options.configura, options.rst, options.outdir)
now = datetime.datetime.now()
ena.show()
diz = {}
diz.setdefault(i,[]).append(t.__name__)
print i.command
2
----> 3 print i.command
4
AttributeError: 'str' object has no attribute 'command'
here you se what they ouptut
"ena."+"".join(diz[id])+"()"
Out[85]: 'ena.trimmomatic()
Definition: ena.trimmomatic(self)
[...]
Any suggestion in how to choose the function to use?
If I understand you correctly you want getattr():

ena = Rnaseq(options.configura, options.rst, options.outdir)
method = getattr(ena, options.step)
method()


_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Loading...