How to Use setattr() Function in PythonPython Basics


The setattr() method sets the value to an object’s attribute.

Example

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

class A(object):
    bar = 1

a=A()
setattr(a, 'bar', 15)
print(a.bar)

Output:

15

Syntax

setattr(object, name, value)

Parameters

Name Description
object The object whose attribute has to be set
name The string which contains the name of the attribute to be set
value Value of the attribute to be set

Return Value

It returns none.

© 2024 Cheerlearn.com, all rights reserved. Privacy Policy | Contact Us