Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use setattr() and getattr() built-ins?

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?

like image 678
temporary_user_name Avatar asked Oct 01 '13 18:10

temporary_user_name


People also ask

What is Setattr () and Getattr () used for?

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.

Why we use Setattr in Python?

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.

What is the usage of Setattr () function?

The setattr() function sets the value of the specified attribute of the specified object.

What is the point of Getattr?

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.


2 Answers

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) 
like image 53
Martijn Pieters Avatar answered Sep 29 '22 12:09

Martijn Pieters


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).

like image 41
BrenBarn Avatar answered Sep 29 '22 11:09

BrenBarn