From reading the docs, I understand exactly what getattr() and setattr() do. But it also says explicitly that getattr(x, 'foobar')
is equivalent to x.foobar
and setattr(x, 'foobar', 123)
is equivalent to x.foobar = 123
.
So why would I use them?
Python setattr() and getattr() goes hand-in-hand. As we have already seen what getattr() does; The setattr() function is used to assign a new value to an object/instance attribute.
Python setattr() function is used to set a value to the object's attribute. It takes three arguments an object, a string, and an arbitrary value, and returns none. It is helpful when we want to add a new attribute to an object and set a value to it.
The setattr() function sets the value of the specified attribute of the specified object.
Python | getattr() method Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key.
Because you can use a dynamic variable too:
somevar = 'foo' getattr(x, somevar)
You can't do that with regular attribute access syntax.
Note that getattr()
also takes an optional default value, to be returned if the attribute is missing:
>>> x = object() >>> getattr(x, 'foo') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'object' object has no attribute 'foo' >>> getattr(x, 'foo', 42) 42
Using getattr()
you can pull the attribute name from something else, not a literal:
for attrname in dir(x): print('x.{} = {!r}'.format(attrname, getattr(x, attrname))
or you can use setattr()
to set dynamic attributes:
for i, value in enumerate(dynamic_values): setattr(i, 'attribute{}'.format(i), value)
You use them if the attribute you want to access is a variable and not a literal string. They let you parameterize attribute access/setting.
There's no reason to do getattr(x, 'foobar')
, but you might have a variable called attr
that could be set to "foobar" or "otherAttr", and then do getattr(x, attr)
.
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