Python setattr() exception

Here we will create read-only attributes of the object using property() function in Python and if we try to set the attribute’s value using setattr() function then an exception will rise.

Python3




class Person:
 
    def __init__(self):
        self._name = None
 
    def name(self):
        print('name function called')
        return self._name
 
    # for read-only attribute
    n = property(name, None)
 
p = Person()
 
setattr(p, 'n', 'rajav')


Output :

---> 16 setattr(p, 'n', 'rajav')
AttributeError: can't set attribute


Python setattr() method

Python setattr() method is used to assign the object attribute its value. The setattr() can also be used to initialize a new object attribute. Also, setattr() can be used to assign None to any object attribute.

Example :

Python3




class Person:
    def __init__(self):
        pass
 
p = Person()
setattr(p, 'name', 'kiran')
print(f"name: {p.name}")


Output :

name: kiran

Similar Reads

Python setattr() Function Syntax

...

Python setattr() Examples

Syntax : setattr(obj, var, val) Parameters :  obj : Object whose which attribute is to be assigned. var : object attribute which has to be assigned. val : value with which variable is to be assigned. Returns : None...

Python setattr() exception

How setattr() works in Python?...