KalelPark's LAB

[ CLEAN CODE ] Clean Python, StaticMethod, ClassMethod란? 본문

Python/CLEAN CODE

[ CLEAN CODE ] Clean Python, StaticMethod, ClassMethod란?

kalelpark 2023. 1. 13. 16:44

StaticMethod, ClassMethod 알아보기

ClassMethod

          - 데코레이터를 사용해서 클래스에 메서드를 선언하면 해당 메서드는 클래스 메서드가 되며,
             첫번째 매개 변수로 클래스 인스턴스가 아닌 클래스 자체가 넘어오게 됩니다.

             관행적으로 cls라고 부르며, 클래스 메서드는 cls를 통하여 속성(attribute)에 접근하거나, 클래스 메서드를 호출할 수 있습니다.

             하지만, 인스턴스 메서드와 달리 인스턴스 속성에 접근하거나 다른 인스턴스 메서드를 호출하는 것은 불가능합니다.

 

class User:
    def __init__(self, email, password):
        self.email = email
        self.password = password

    @classmethod
    def fromTuple(cls, tup):
        return cls(tup[0], tup[1])

    @classmethod
    def fromDictionary(cls, dic):
        return cls(dic["email"], dic["password"])

          - 예시를 들면, 위의 User클래스는 생성자인 1개의 인스턴스 메서드와          
             @classmethod 어노테이션이 달린 2개의 클래스 메서드로 이루어져있다.
             fromTuple 과 fromDictionary에는 cls 매개변수가 할당되어 있습니다.
             Tuple은 Tuple타입, Dictionary는 Dictionary타입을 받는다.

>>> user = User.fromTuple(("user@test.com", "1234"))
>>> user.email, user.password
('user@test.com', '1234')

StaticMethod

       - 첫 번째 매개변수가 할당되지 않습니다. 따라서 정적 메서드 내에서는 인스턴스/클래스 속성에 접근하거나,
           인스턴스/클래스 메서드를 호출하는 것은 불가능합니다.

class StringUtils:
    @staticmethod
    def toCamelcase(text):
        words = iter(text.split("_"))
        return next(words) + "".join(i.title() for i in words)

    @staticmethod
    def toSnakecase(text):
        letters = ["_" + i.lower() if i.isupper() else i for i in text]
        return "".join(letters).lstrip("_")

 

       -  정적 메서드는 유틸리티 메서드를 구현할 때 많이 사용된다.

           위의 StringUtils 클래스는 2개의 정적 메서드로 이루어져 있다.

>>> StringUtils.toCamelcase("last_modified_date")
'lastModifiedDate'
>>> StringUtils.toSnakecase("lastModifiedDate")
'last_modified_date'

 

 

 

Comments