85

How can I achieve such job:

def get_foo(someobject, foostring):
    return someobject.foostring

IE:

if I do get_foo(obj, "name") it should be calling obj.name (see input as string but I call it as an attritube.

Thanks

2

3 Answers 3

122

Use the builtin function getattr.

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

1
  • that's a huge blessing that we can do that =) Aug 21, 2021 at 6:50
53

If someobject has an attribute named foostring then

def get_foo(someobject, foostring):
    return getattr(someobject,foostring)

or if you want to set an attribute to the supplied object then:

def set_foo(someobject, foostring, value):
    return setattr(someobject,foostring, value)

Try it

36

You should use setattr and getattr:

setattr(object,'property',value)
getattr(object,'property',default)

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.