반응형
문자열에 객체와 메서드 이름이있는 경우 메서드를 어떻게 호출 할 수 있습니까?
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
반응형
'파이썬' 카테고리의 다른 글
파이썬 ImportError : pydot라는 모듈이 없습니다 (pydot를 가져올 수 없음). (0) | 2020.11.10 |
---|---|
파이썬 Python 목록 함수 인수 이름 (0) | 2020.11.10 |
파이썬 Add another tuple to a tuple of tuples (0) | 2020.11.09 |
파이썬 Python string.replace ()가 문자를 대체하지 않음 (0) | 2020.11.09 |
파이썬 Python 2의 유형 힌트 (0) | 2020.11.09 |
댓글