w3resource

Python: setattr() function

setattr() function

The setattr() function is used to set the value of the specified attribute of the specified object.

Version:

(Python 3.2.5)

Syntax:

setattr(object, name, value)

Parameter:

Name Description Required /
Optional
object An object. Required.
name The name of the attribute to be set. Required.
value The value you want to give the specified attribute Required.

Example: Python setattr() function

class Person:
    name = 'Bishop'
    
p = Person()
print('Before modification:', p.name)

# setting name to 'David'
setattr(p, 'name', 'David')

print('After modification:', p.name)

Output:

Before modification: Bishop
After modification: David

Python Code Editor:

Previous: set()
Next: slice()

Test your Python skills with w3resource's quiz



Follow us on Facebook and Twitter for latest update.