Python, using two variables in getattr?
I'm trying to do the following:
import sys; sys.path.append('/var/www/python/includes')
import functionname
x = 'testarg'
fn = "functionname"
func = getattr(fn, fn)
func (x)
but am getting an error:
"TypeError: getattr(): attribute name must be string"
I have tried this before calling getattr but it still doesn't work:
str(fn)
I don't understand why this is happening, an开发者_如何学Cy advice is appreciated
It sounds like you might be wanting locals()
instead of getattr()
...
x = 'testarg'
fn = "functionname"
func = locals()[fn]
func (x)
You should be using getattr when you have an object and you want to get an attribute of that object, not a variable from the local namespace.
The first argument of getattr is the object that has the attribute you are interested in. In this case you are trying to get an attribute of the function, I assume. So the first argument should be the function. Not a string containing the function name, but the function itself.
If you want to use a string for that, you will need to use something like locals()[fn] to find the actual function object with that name.
Second, you're passing the function name to getattr twice. The function doesn't have itself as an attribute. Did you mean the second argument to be x? I don't really get what you're trying to do here, I guess.
精彩评论