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 tox.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
Plotting Grouped Data in Same Plot Using Pandas
Function with Varying Number of for Loops (Python)
Update Tkinter Label from Variable
How Can Strings Be Concatenated
Typeerror: Worker() Takes 0 Positional Arguments But 1 Was Given
Reducing Size of Pyinstaller Exe
Split a List into Parts Based on a Set of Indexes in Python
Find Longest Repetitive Sequence in a String
Django Smtpauthenticationerror
How to Get All the Contiguous Substrings of a String in Python
Pandas: Filtering Multiple Conditions
How to Delete All Blank Lines in the File with the Help of Python
Concatenate Numpy Arrays Without Copying
Import a Python Module Without the .Py Extension
Matplotlib Axes.Plot() VS Pyplot.Plot()