Python String to Attribute

Python string to attribute

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.

How to turn a string into an attribute?

you just have to do:

getattr(commander, cmd)()

How to access (get or set) object attribute given string corresponding to name of that attribute

There are built-in functions called getattr and setattr

getattr(object, attrname)
setattr(object, attrname, value)

In this case

x = getattr(t, 'attr1')
setattr(t, 'attr1', 21)

Use string to get attribute value python

__getattr__ is called if A().a doesn't exist. You still need to use getattr if the attribute itself is a variable.

def use_a(self, attribute='a'):
a = getattr(A(), attribute)
return a

How to convert string to class sub-attribute with Python

The operator.attrgetter function does this:

class Foo: pass
f = Foo()
f.bar = Foo()
f.bar.baz = Foo()
f.bar.baz.quux = "Found me!"

import operator
print operator.attrgetter("bar.baz.quux")(f) # prints "Found me!"

Convert string to property - AttributeError: can't set attribute

Steve's solution above worked for me.
pypi.org/project/attributedict



Related Topics



Leave a reply



Submit