CS/Python

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

Tigris 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