Skip to content

[Python] How to use setattr() function and getattr() function

Last Updated on 2021-05-21 by Clay

In Python, setattr() and getatter() are functions that often used together.

setattr() can set the value of the variable defined in the class, and getattr() can get the value of the variable defined in the class.

Let's take a look for a simple sample code:

# -*- coding: utf-8 -*-


class test(object):
    a = 123
    b = 'today'


print(getattr(test, 'a'))
print(getattr(test, 'b'))



Output:

123
today

First, we define the class test and the variables a and b contained in it. Then externally, we can get the values of these two variables through getattr().

The usage of setatter() function is simple too.

# -*- coding: utf-8 -*-


class test(object):
    a = 123
    b = 'today'



setattr(test, 'a', 777)
setattr(test, 'b', 'yesterday')
print(getattr(test, 'a'))
print(getattr(test, 'b'))


Output:

777
yesterday

This time, since we set it in advance, the values obtained by getattr() are 777 and yesterday respectively.

These two functions are very convenient when adjusting program parameters.

Tags:

Leave a Reply