Next / Previous / Contents / Shipman's homepage

21.18. setattr(): Set an attribute

This function is the inverse of Section 21.8, “getattr(): Retrieve an attribute of a given name”: it sets the value of some attribute whose name is A from an instance I to a new value V:

setattr(I, A, V)


>>> class C5:
...     def __init__(self, x):
...         self.x = x
>>> c=C5(14)
>>> c.x
>>> setattr(c, 'x', 19)
>>> c.x
>>> setattr(c, 'violateEncapsulation', True)
>>> c.violateEncapsulation

As the last lines above show, you can use this function to create attributes that didn't even exist before. However, this is often considered bad style, as it violates the principle of encapsulation.