Table of Contents
In this tutorial, we will learn about the Python setattr() function with the help of examples.
The setattr() function sets the value of the attribute of an object.
Example
class Student: marks = 88 name = 'Sheeran' person = Student() # set value of name to Adam setattr(person, 'name', 'Adam') print(person.name) # set value of marks to 78 setattr(person, 'marks', 78) print(person.marks) # Output: Adam # 78
1. setattr() Syntax
The syntax of the setattr() function is:
setattr(object, name, value)
If you want to get the attribute of an object, use getattr().
2. setattr() Parameters
The setattr() function takes three parameters:
- object – object whose attribute has to be set
- name – attribute name
- value – value given to the attribute
3. setattr() Return Value
The setattr() method returns None.
4. Example 1: How setattr() works in Python?
class Person:
name = 'Adam'
p = Person()
print('Before modification:', p.name)
# setting name to 'John'
setattr(p, 'name', 'John')
print('After modification:', p.name)
Output
Before modification: Adam After modification: John
5. Example 2: When the attribute is not found in setattr()
If the attribute is not found, setattr() creates a new attribute an assigns value to it. However, this is only possible if the object implements the __dict__() method.
You can check all the attributes of an object by using the dir() function.
class Person:
name = 'Adam'
p = Person()
# setting attribute name to John
setattr(p, 'name', 'John')
print('Name is:', p.name)
# setting an attribute not present in Person
setattr(p, 'age', 23)
print('Age is:', p.age)
Output
Name is: John Age is: 23
Related posts:
Python isinstance()
Python Program to Add Two Numbers
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python Program to Get the File Name From the File Path
Python int()
Python Namespace and Scope
How to get current date and time in Python?
Python Program to Merge Two Dictionaries
Python String ljust()
Python File I/O Operation
Python Program to Get the Full Path of the Current Working Directory
Python Program to Get Line Count of a File
Python Modules
Python Program to Convert String to Datetime
Python Decorators
Python String lstrip()
Python Dictionary get()
Python Program to Check if a Key is Already Present in a Dictionary
Python Program to Print Hello world!
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Program to Find Armstrong Number in an Interval
Python datetime
Python String isspace()
Python Program to Check If Two Strings are Anagram
Python any()
Python Program to Find Hash of File
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python hasattr()
Python Dictionary setdefault()
Python Program to Differentiate Between type() and isinstance()
Python String split()