Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
05-16 20:20
관리 메뉴

nomad-programmer

[Programming/Python] Class Method & Static Method 본문

Programming/Python

[Programming/Python] Class Method & Static Method

scii 2021. 2. 8. 20:25

클래스 메서드(class method)와 정적 메서드(static method)가 어떻게 다른지 예제를 보며 살펴보자.

class MethodClass:
    @staticmethod
    def static_method():
        print('static method')

    @classmethod
    def class_method(cls):
        print(cls.__name__)


if __name__ == '__main__':
    stc_mtd = MethodClass()
    stc_mtd.static_method()
    stc_mtd.class_method()

""" 결과

static method
MethodClass

"""

static_method() 함수는 정적 메서드이다. 정적 메서드는 인자로 클래스나 객체를 받지 않는다. 함수의 정의만 클래스 MethodClass의 네임스페이스에 있을 뿐 일반 함수와 같으며 전역 함수를 대체하기에 가장 알맞다.

class_method() 는 클래스 메서드이다. 첫 번째 인자로 클래스 MethodClass를 받는다. 두 메서드의 타입을 확인해보자.

print(type(stc_mtd.static_method))
print(type(stc_mtd.class_method))

""" 결과

<class 'function'>
<class 'method'>

"""

클래스 메서드는 대체 생성자로도 쓰인다. 다음의 예를 보자.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def init_from_string(cls, string: str):
        name, age = string.split('_')
        return cls(name, int(age))


if __name__ == '__main__':
    p = Person.init_from_string('hahaha_23');
    print(p.name)
    print(p.age)


""" 결과

hahaha
23

"""

init_from_string() 메서드는 <name>_<age> 형태의 문자열을 인자로 받아 이를 분석하여 일반적인 생성자를 다시ㅐ 호출한다.

이렇게 메서드를 설계해 두면 필요할 때마다 클래스 메서드를 호출해서 객체를 만들 수 있어 편리하다.

Comments