내가 한 노력들

[ Python ] 변수에 따른 함수를 실행시키고 싶은 경우 (getattr) 본문

IT 공부/python

[ Python ] 변수에 따른 함수를 실행시키고 싶은 경우 (getattr)

JONGI-N CHOI 2022. 2. 28. 15:45

getattr( object, attribute name )

class Graph:

    @staticmethod
    def barGraph(x, y):
    	print('x축의 값이 {}이고 y축의 값이 {}인 bar 그래프.'.format(x, y))
 
    @staticmethod
    def pieGraph(x, y):
    	print('x축의 값이 {}이고 y축의 값이 {}인 pie 그래프.'.format(x, y))

    @staticmethod
    def scatterGraph(x, y):
    	print('x축의 값이 {}이고 y축의 값이 {}인 scatter 그래프.'.format(x, y))

arr = ['bar', 'pie', 'scatter']

for graph in arr :
	getattr(Graph, graph + 'Graph')('성별', '평균수명')
    
    
# 결과
x축의 값이 나이이고 y축의 값이 평균수명인 bar 그래프.
x축의 값이 나이이고 y축의 값이 평균수명인 pie 그래프.
x축의 값이 나이이고 y축의 값이 평균수명인 bscatterar 그래프.

getattr는 object 안에 찾고자하는 attribute의 값을 출력합니다. 

 

 

만약에 attribute가 존재하지 않는 경우

getattr를 사용할 때, default값을 설정해줄 수 있습니다. 

getattr( object, attribute name [, default] )

getter ( Graph, 'barhGraph', '해당 object 에 {}라는 attribute는 존재하지 않습니다.'.format())(x, y)

#결과 
Graph라는 object에 barhGraph라는 attribute는 존재하지 않습니다.

 

아니면 try, except를 통해서 처리해주는 방법도 존재합니다. 

for graph in arr:
    try:
        getattr(Graph, graph + 'Graph')('성별', '평균수명')
    except AttributeError as e:
        print("Unknown statistic: " + graph)