Tigris
묵묵히 걸어가기
Tigris
전체 방문자
오늘
어제
  • 분류 전체보기 (40)
    • CS (15)
      • Algorithms (1)
      • Linux (3)
      • Python (4)
      • Git & Github (2)
      • Cloud Service (1)
    • Data Science (8)
      • Maching Learning (9)
      • Framework (1)
    • Notes (2)
    • Data (4)

태그

  • 어텐션
  • 트랜스포머
  • 나는리뷰어다
  • 파이썬
  • 한빛미디어
  • attention
  • Deep learning
  • python
  • Transformer
  • 딥러닝
hELLO · Designed By 정상우.
Tigris

묵묵히 걸어가기

CS/Python

[Python] Class에서 특정 문자열로 시작하는 Method 찾기

2022. 5. 25. 19:33

파이썬에서 Class 내에서 특정 문자열로 시작하는 이름을 가진 Method를 확인하는 방법을 알아보겠습니다.

사용 함수

dir()

dir() 함수를 이용하면 입력된 Class 또는 Instance 내 모든 Attribute의 이름이 담긴 리스트가 반환됩니다.

callable()

Callable 여부에 따라 주어진 Attribute가 Class / Instance Variable와 Method 중 어느 것에 해당하는지 식별할 수 있습니다.

Example

다음과 같이 정의된 Class가 존재한다고 가정하겠습니다.

class Example:
    class_variable = 5
    
	def __init__(self):
        self.instance_varibale = 3
    
	def say_hello(self):
        return "Hello"

우선 Example Class가 가진 Attribute 목록을 확인해보겠습니다.

dir(Example)

# ['__class__', '__dict__', ... , '__weakref__', 'class_variable', 'say_hello']

class_variable, say_hello 등 Example Class가 가진 Attribute의 이름이 모두 출력된 것을 볼 수 있습니다. (cf. instance_variable의 경우 Instance가 생성될 때 정의되므로 Example의 Attribute 목록에는 존재하지 않습니다 🙂 )

그럼 dir 함수를 이용해 알아낸 Attribute 이름 중 say로 시작하는 Method가 있는지 확인해보겠습니다.

for name in dir(Example):
	has_prefix = name.startswith("say")
    
	attribute = getattr(Example, name)
    is_method = callable(attribute)

    if has_prefix and is_method:
        print(name)

# say_hello

잘못된 내용, 오타, 부정확한 문장 등 어떤 피드백이든 환영합니다. 감사합니다.


References

  • https://docs.python.org/2/library/functions.html#callable
  • https://docs.python.org/2/library/functions.html#dir
저작자표시 비영리 변경금지 (새창열림)

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

[FastAPI]FastAPI의 비동기 함수 동작 방식  (0) 2023.03.24
[FastAPI]FastAPI의 동기 함수 동작 방식  (0) 2023.03.21
[Python] 주어진 문자열이 알파벳/숫자로만 구성되었는지 확인해보기  (0) 2022.04.20
    'CS/Python' 카테고리의 다른 글
    • [FastAPI]FastAPI의 비동기 함수 동작 방식
    • [FastAPI]FastAPI의 동기 함수 동작 방식
    • [Python] 주어진 문자열이 알파벳/숫자로만 구성되었는지 확인해보기
    Tigris
    Tigris
    Data Science, Data Engineering, 그리고 Data Product와 관련된 이야기를 함께 나누고 싶습니다.

    티스토리툴바