Python Tutorial Python Advanced Python References Python Libraries

Python setattr() Function



The Python setattr() function is used to assign a new value to the specified attribute of the specified object. If the required attribute is not found in the object, the method does not raises any exception.

Syntax

setattr(object, attribute, value)

Parameters

object Required. An object
attribute Required. attribute which need to checked in object.
value Required. value which need to be assigned to the given attribute.

Example:

In the example below, setattr() function is used to assign a new value to the specified attribute of the given class.

class MyClass:
  name = "John"
  age = 25
  city = "London"

print(getattr(MyClass, 'age'))
setattr(MyClass, "age", 40)
print(getattr(MyClass, 'age'))

The output of the above code will be:

25
40

❮ Python Built-in Functions