본문 바로가기
파이썬

파이썬 이름으로 Python 메서드 호출

by º기록 2020. 11. 10.
반응형

문자열에 객체와 메서드 이름이있는 경우 메서드를 어떻게 호출 할 수 있습니까?

class Foo:
    def bar1(self):
        print 1
    def bar2(self):
        print 2

def callMethod(o, name):
    ???

f = Foo()
callMethod(f, "bar1")

 

해결 방법

 


class Foo:
    def bar1(self):
        print(1)
    def bar2(self):
        print(2)

def call_method(o, name):
    return getattr(o, name)()


f = Foo()
call_method(f, "bar1")  # prints 1


 

참조 페이지 https://stackoverflow.com/questions/3521715

 

 

반응형

댓글