ScanSkill

setattr

This setattr() function assigns a value to the object’s attribute given its name.

Syntax

setattr(object, name, value)

Here,

  • object: Required. An object whose attributes will be changed.
  • name: Required. A string name of the attribute.
  • value: Required. A new value of any type.

Note: Note that setattr(x, ‘foobar’, 123) is equivalent to x.foobar = 123.

Examples

>>> class Class1:
...     def __init__(self, x):
...         self.x = x
...
>>> f = Class1(10)
>>> f.x
10
>>> setattr(f, 'x', 20)
>>> f.x
20
>>> setattr(f, 'y', 10)
>>> f.y
10
>>> f.y = 100
>>> f.y
100

Function as a method to a class dynamically

>>> # you can dynamically add a function as a method to a class
>>> def func1(self):
...     print('Hello')
... 
>>> class Class1:
...     pass
... 
>>> f = Class1()
>>> print(dir(f))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] 

>>> setattr(Class1, 'hello', func1)
>>> print(dir(f))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'hello']
>>> f.hello()
Hello

Here, class func1 is passed to Class1 as a method with the help of setattr() function.