Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries


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 below example, 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