[英]python passing a variable to an object property or method through a function argument
I've been trying to construct a generic function (a Django view handler) whose arguments are contains specific object property to use inside the function 我一直在尝试构造一个泛型函数(Django视图处理程序),其参数包含要在函数内部使用的特定对象属性
something like (simplified): 类似于(简化):
def some_function(arg, property):
return Some_Object.property
but python tries to treat 'property' as the property/method name instead of treating it like a variable. 但是python尝试将“属性”视为属性/方法名称,而不是将其视为变量。
I tried multiple variants but none worked. 我尝试了多种变体,但没有一个起作用。 (didn't try exec/eval varient - should I? doesn't seem too pythonic)
(没有尝试exec / eval变量-我应该吗?似乎不太pythonic)
I know that I can pass a function or an object as an argument. 我知道我可以将函数或对象作为参数传递。 but didn't seem to find the exact solution here using python 2.7 and 2.6
但似乎没有找到使用python 2.7和2.6的确切解决方案
the specific implantation is a Django issue but I got curious about this 具体的植入是Django问题,但对此我感到好奇
I think what you want to do is use getattr to retrive the property: 我认为您要使用getattr检索属性:
def some_function(arg, property):
return getattr(Some_Object, propery)
You can see the documentation here: http://docs.python.org/library/functions.html#getattr 您可以在此处查看文档: http : //docs.python.org/library/functions.html#getattr
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.