Python access member as string

2021. 12. 10. 13:50Programming/Python

    목차
반응형

You from time to time meet a case that you need to set member varialbe. In such a case, if you get a class with lots of member varialbe, then code to set/get is somewhat burden.
In such case, there are very simple way to do. I'll let you know in this article.

class definition

Assume that there is a class with three member attributes as follow.

class Item:
    def __init__(self):
        self.key = None
        self.cat = None
        self.file = None

regular way to set

Regular way to set values to attributes is like this.

item = Item()

item.key = 1
item.cat = 3
item.file = 'filename'

In case above, the total number of attributes is just three. So, it is very easy to do. But, imagine that there is a class with lots of member attributes more than dozens. It must be very irksome.

setattr

Yes, in order to handle this situation easily, you can use 'setattr'.
Okay, first, just declare a list that has member name and value to set.

attrs = [
    ('key', 20), ('cat', 5), ('file', 'file1.txt)
]

for member, value in attrs:
    setattr(item, member, value)

getattr

Oppositely, you can use getattr to get the value of each attribute.

for member, value in attrs:
    val = getattr(item, member)
반응형

'Programming > Python' 카테고리의 다른 글

Python instance check  (0) 2021.12.13
[Python] Lambda expression (람다 표현식)  (0) 2021.12.13
Python access member with string  (0) 2021.12.10
openpyxl sheet  (0) 2021.12.10
openpyxl sheet  (0) 2021.12.10