简体   繁体   中英

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

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.

I tried multiple variants but none worked. (didn't try exec/eval varient - should I? doesn't seem too 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

the specific implantation is a Django issue but I got curious about this

I think what you want to do is use getattr to retrive the property:

def some_function(arg, property):
    return getattr(Some_Object, propery)

You can see the documentation here: http://docs.python.org/library/functions.html#getattr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM