setattr() vs. Regular Assignment | Sololearn: Learn to code for FREE!

+2

setattr() vs. Regular Assignment

I recently learned about the setattr() function in Python. What makes this function different than just assigning the new attribute? Like this: # setattr() class Thing: def __init__(self, x): self.x = x something = Thing(5) setattr(something, 'y', 10) # Adds a 'y' attribute to 'something' # vs. this: class Thing: def __init__(self, x): self.x = x something = Thing(5) something.y = 10 # Also adds a 'y' attribute to 'something'

4/16/2021 3:10:59 AM

McInventor29

4 Answers

New Answer

+3

McInventor29 after doing a little digging I found this and hope it helps. I rarely see setattr() without getattr() usually as referenced: which is also cited in the link. Setattr: We use setattr to add an attribute to our class instance. We pass the class instance, the attribute name, and the value. and with getattr we retrieve these values. https://stackoverflow.com/questions/9561174/using-setattr-in-python

+2

BroFar: Thanks, that helped a lot! Myk Dowling: Ohhh, I can see why you would need it there. Thanks for the example!

+1

Setattr lets you write code to set items in an object without knowing beforehand what attributes you want to set. eg. def set_attributes(item, values): for attrib in values: setattr(item, attrib, values[attrib]) set_attributes_from_triggers(an_object, {'attrib1':`0, 'attrib2': 'data'}) Imagine loading in that dictionary from a JSON file, or via a REST API.

0

The main difference between the setattr() function and the regular assignment is that the regular assignment using the dot(.) operator can only set static attributes to the object. But, the setattr() function is not restricted to this. Using the setattr() function you can dynamically set the new attributes to the given object. This becomes very helpful where the user enters what attribute needs to be added to the object. You can find the detailed explanation here https://programmersportal.com/python-setattr-function/