Python,在getattr中使用两个变量? [英] Python, using two variables in getattr?
本文介绍了Python,在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)
但出现错误:
"TypeError: getattr(): attribute name must be string"
在调用getattr之前,我已经尝试过了,但是仍然无法正常工作:
I have tried this before calling getattr but it still doesn't work:
str(fn)
我不明白为什么会这样,感谢任何建议
I don't understand why this is happening, any advice is appreciated
推荐答案
听起来您可能想要的是locals()
而不是getattr()
...
It sounds like you might be wanting locals()
instead of getattr()
...
x = 'testarg'
fn = "functionname"
func = locals()[fn]
func (x)
当您有一个对象并且想要获取该对象的属性而不是本地名称空间中的变量时,应该使用getattr.
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.
这篇关于Python,在getattr中使用两个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文