클래스에서 @staticmethod와 @classmethod의 차이

딥러닝견습생·2022년 1월 3일
0

클래스를 배우다보면 두가지 추가개념이 등장한다.
@staticmethod와 @classmethod

이 두가지 개념은 추상적으로 아래와 같이 구분할 수 있다.

@staticmethod: 클래스 내에서 구현하지만 클래스에 접근하지 않고 독립적인 행위를 하는
@classmethod: 클래스를 생성하지 않고도 클래스에 접근하여 무언갈 하는

코드로 확인해보면

class TextManager:
    @staticmethod
    def is_korean(txt):  # 클래스 내부로의 접근이 없다
        "txt가 한국어 인가요?"
        match = re.search(r"[ㄱ-ㅎ|ㅏ-ㅣ|가-힣]", txt or "")
        return match is not None
    
    @classmethod
    def language_classification(cls, txt):  # 클래스 내부의 is_korean 을 쓴다
        "언어 판별"
        return "korean" if cls.is_korean(txt) else "others"

@staticmethod는 cls 인자를 받지 않지만
@classmethod는 cls 인자를 받는다.
이 cls는 클래스 자신을 의미한다.

외부에서 is_korean("한국어") 함수를 사용하고 싶다면 @staticmethod로 선언한다.
TextManager를 만들면서 한글을 판별하는 메소드를 만들었으니, 다른 곳에서 재작성 할 필요 없이 바로 가져다 쓸 때!

chk_korean = TextManager.is_korean("안녕하세요")
print(chk_korean)  # True

마찬가지로 외부에서 language_classification("텍스트") 함수를 사용하고 싶다면 @classmethod로 선언한다. 단, 이는 클래스 내부의 변수나 함수에 접근해야할 때 사용한다

language = TextManager.language_classification("Hello")
print(language)  # others

0개의 댓글