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



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python/built-in-function/setattr.php