[Python] getattr() 특정 문자열의 이름을 가지는 attribute 반환

2023. 7. 20. 16:01

getattr(object, name) / getattr(object, name, default)

python docs
Return the value of the named attribute of object. (name must be a string.) object의 name으로 불리는 attribute값을 반환한다. (이때 name은 문자열)
If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. object의 attribute로 'name'이 있다면 반환값은 이 attribute값이다.
마찬가지로 'name'이 object의 class, method에 해당한다면 이 자체를 반환함. 따라서 인자를 붙이면 클래스 생성, 함수 호출이 가능함.
If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised. 만약 default 인자가 지정되어있지 않고, 'name' attribute가 없다면 AttributeError를 일으킨다. 하지만 만약 default 인자가 지정되어 있다면 default를 반환한다.

Example:

class Models:
    class model1:
        def __init__(self, opts):
            print("model1")
    class model2:
        def __init__(self, opts):
            print("model2")
    class model3:
        def __init__(self, opts):
            print("model3")

(가정) Models 패키지 안에 model1, model2, model3가 구현되어 있다. 실험을 위해 모델을 바꾸어가며 여러번 실행해보려고 한다. 이때 코드 실행시 모델 생성 부분을 직접 수정하지 않고 getattr(...)를 사용해보면 다음과 같다.

import argparse

parser = argparse.ArgumentParser(description='getattr parser')
parser.add_argument('--model_name', default='model1', type=str, help='model name')
opts = parser.parse_args(args=[])


getattr(Models, opts.model_name)(opts)

getattr(Models, opts.model_name) : Models 패키지 안의 'opts.model_name'의 이름을 가지는 attribute를 반환한다.
즉, _class가 반환_되므로 opts 인자를 넘겨주면 해당 객체를 생성할 수 있다.
다른 model로 바꾸고 싶다면 parsermodel_name만 바꿔주면 쉽게 실행이 가능해진다.

참고

[Python] 내장함수 getattr()를 활용해 코드 간소화 시키기|작성자 Paris Lee

BELATED ARTICLES

more