Methods and Functions

Python setattr()

banners

Python setattr() function is used to assign a new value to the attribute of an object/instance. Setattr in python sets a new specified value argument to the specified attribute name of a class/function’s defined object.

Sometimes a situation arises where an attribute has already been assigned a value in the class or function, but the programmer needs to change it as per their needs. In such situations, setattr in python comes to the rescue. Python setattr() is a built-in function that helps the user change an object’s attribute value by explicitly defining it.

setattr in python

Setattr python

This method provides an alternate means to assign values to class variables, in addition to constructors and object functions. It comes in handy when we want to add a new attribute to an object and assigning it a value. The Python setattr() function accepts 3 parameters. The syntax is as follows:

Syntax for python setattr

                    
setattr(object, name, value)

python setattr Parameters 

  1. object = instance of the function whose attribute is to be set
  2. name = variable name/attribute name
  3. value = value to be set for the attribute

Return value of setattr python

The setattr() function returns None value.

Example 1: How setattr() works in Python?

When we specify the attribute name parameter to assign a value in the setattr() function, note that we must always enclose it with quotes or apostrophes i.e. “ ” or ‘ ’. This attribute name parameter should be passed as a string value.

Example

                    
# Python program to illustrate setattr() function
class Details:
    name = 'Sam'
    age = 24

# Create an object of the class
d = Details()

print('Name before modification:', d.name)
print('Age before modification:', d.age)

setattr(d, 'name', 'Timmy')
setattr(d, 'age', 27)

print('Name after modification:', d.name)
print('Age after modification:', d.age)

Output

                    
Name before modification: Sam
Age before modification: 24
Name after modification: Timmy
Age after modification: 27

Note – The attribute parameter in the setattr() function is case-sensitive. Hence, double-check before using the attribute names to change their values.

Example 2: When an attribute is not found in setattr python

One of the most important properties of setattr() is that it can be used to create and initialize a new attribute in the object if it is not found. We can assign the ‘None’ value to the attribute. We can also assign a numeric or alphabetical value to the newly created attribute.

Example

                    
# Python program to illustrate setattr() function
class Car:
    brand = 'BMW'

# Create an object of the class
c = Car()
setattr(c, 'brand', 'Jaguar')
print('New Car brand value:', c.brand)

setattr(c, 'type', None)
print('After setattr type:', c.type)

setattr(c, 'price', 35000)
print('After setattr price:', c.price)

Output

                    
New Car brand value: Jaguar
After setattr type: None
After setattr price: 35000

FAQs on setattr in python

Q1. What is setattr in Python?

Sometimes a situation arises where an attribute has already been assigned a value in the class or function, but the programmer needs to change it as per their needs. For this purpose, Python provides a setattr() built-in function which is used by the programmers to efficiently change the attribute values of an object in the program.

Q2. What is setattr() used for?

The Python setattr() function sets a new specified value argument to the specified attribute name of a class/function’s defined object. This method provides an alternate means to assign values to class variables, in addition to constructors and object functions. It comes in handy when we want to add a new attribute to an object and assigning it a value. The Python setattr() function accepts 3 parameters. It accepts the object name, attribute name, and value as inputs and sets object attribute to value.

Syntax

                    
setattr(object, attribute, value)

Example

                    
# Python program to illustrate setattr() function
class Sports:
    category = 'Athletics'

# Create an object of the class
s = Sports()
print('Old Sports category value:', s.category)

setattr(s, 'category', 'Cricket')
print('New Sports category value:', s.category)

Output

                    
Old Sports category value: Athletics
New Sports category value: Cricket

Q3. What are getattr and setattr in Python?

Python setattr() and getattr() goes hand-in-hand. As we have already seen what setattr() does; The getattr() function in Python is being used to retrieve the value of an object’s attribute; and if no attribute of that object is discovered, the default value is returned. The function getattr() supports many parameters.

Syntax

                    
getattr(object, attribute, default_value)

where,

default_value = When an attribute is not found, this specified value is returned

Example

                    
class Employee:
    company = 'Microsoft'
    name = 'Eric Williams'
    age = 30

e = Employee()

setattr(e, 'company', 'Apple')
print('New company:', e.company)

print(getattr(e, 'name', 'John Hastings'))  # as name attribute is already present in class Employee, it will print the original value
print(getattr(e, 'salary', 25000))   # salary attribute not found, it prints default value 25000

Output

                    
New company: Apple
Eric Williams
25000

Q4. What does AttributeError mean in Python?

When you try to call an attribute of an object whose type does not support that function, Python throws an AttributeError. In Python, AttributeError is an error that occurs when an attribute reference or assignment fails. Though there are few chances of getting this error, the probability cannot be ignored completely. Let us understand this error by looking at the following example.

Example 1

Output

                    
Traceback (most recent call last):
File "", line 2, in 
AttributeError: 'int' object has no attribute 'append'

In the above program, we try to append an integer value to a variable that has stored another integer value. Logically this is not possible and even Python does not support this. Hence the Python compiler throws an AttributeError exception.

Example 2

                    
class Person:
    def __init__(self):
        self.name = 'John'

obj = Person()

print(obj.name)
print(obj.city)

Output

                    
John
Traceback (most recent call last):
File "", line 7, in 
AttributeError: 'Person' object has no attribute 'city'

Share with friends
image
image
Customize your course in 30 seconds

Which class are you in?

5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started
Customize your course in 30 seconds

Which class are you in?

No thanks.