Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string to attribute

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

like image 731
Hellnar Avatar asked Jul 15 '10 08:07

Hellnar


People also ask

How do I convert a string to an object in Python?

Use the json.loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary. This process is called deserialization – the act of converting a string to an object.

How do you call an attribute in Python?

Attributes of a class can also be accessed using the following built-in methods and functions : getattr() – This function is used to access the attribute of object. hasattr() – This function is used to check if an attribute exist or not. setattr() – This function is used to set an attribute.

What is __ Getattribute __ in Python?

__getattribute__This method should return the (computed) attribute value or raise an AttributeError exception. In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.


2 Answers

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.

like image 148
adamk Avatar answered Sep 20 '22 09:09

adamk


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

like image 40
Nazmul Hasan Avatar answered Sep 22 '22 09:09

Nazmul Hasan