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
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.
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.
__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.
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 tox.foobar
. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With