이동식 저장소

static method, class method, abstract method 본문

Secondary/Python

static method, class method, abstract method

해스끼 2023. 3. 1. 18:04

파이썬 클래스에 선언할 수 있는 static method, class method, abstract method에 대해 알아보자.

Static method

클래스 자체의 method이다. 객체가 아닌 클래스의 method이므로 객체 자신을 참조하는 `self` 매개변수가 없으며, 클래스 참조만으로 사용할 수 있다.

class MyClass:
    def static_method():
        print('This is static method.')

MyClass.static_method()

유틸리티 함수를 만들 때 유용하게 사용할 수 있다.

Class method

클래스 자체의 method라는 점은 static method와 같지만, 다른 점도 많다.

class MyClass:
    @classmethod
    def class_method(cls):
        print(f'This is class method of {cls}.')
	
MyClass.class_method()
# This is class method of <class '__main__.MyClass'>.

우선 Class method를 선언하려면 `c lassmethod`라는 데코레이터를 붙여야 한다. 또, Class method에는 적어도 하나의 매개변수(클래스 참조자)가 선언되어야 한다. 클래스 참조자를 사용하면 클래스 자체에 접근할 수 있다. 관례적으로 `self`로 쓰는 객체 참조자처럼 클래스 참조자도 보통 `cls`로 쓴다.

 

함수 내부에서 static variable에 접근하고 싶다면 static method 대신 class method를 사용해 보자.

class MyClass:
    num = 10

    def static_method():
        print(MyClass.num)

    @classmethod
    def class_method(cls):
        print(cls.num)        # 이게 조금 더 깔끔..?

`cls`를 이용하여 객체를 만들 수도 있다. 클래스 이름으로 객체를 만드는 코드와 완전히 같다.

class MyClass:
    name: str

    def __init__(self, name: str):
        self.name = name
    
    @classmethod
    def instantiate(cls, name: str):
        return cls(name)

MyClass.instantiate('mwy3055').name
# mwy3055

함수 내부에서 Static variable에 접근해야 한다면 class method를 사용해 보자.

Abstract method

객체지향 프로그래밍의 추상 메서드이다. 

 

Abstract method는 함수의 매개변수와 리턴 타입만 정의되어 있고, 본문은 정의되지 않은 함수이다. 그럼 본문은 어디 있느냐? 본문은 자신을 상속한 하위 클래스에서 정의해야 한다. 정의하지 않으면 해당 하위 클래스의 인스턴스를 만들 수 없다.

# test.py
from abc import ABCMeta, abstractmethod


class BaseClass(metaclass=ABCMeta):
    @abstractmethod
    def method():
        pass


class SubClass(BaseClass):
    # abstract method를 정의하지 않으면
    pass
import test
test.SubClass() # 에러!

하위 클래스에서 정의할(그리고 정의해야 하는) 함수는 abstract method로 선언하자.

 

Abstract method는 static method나 class method와 전혀 관계없으며, 메서드가 가질 수 있는 속성 중 하나라고 보면 된다. Static method와 class method도 메서드의 속성이기 때문에 이 둘을 결합하여 abstract static method와 abstract class method를 선언할 수 있다. 이 메서드들은 abstract method와 static(class) method의 속성을 모두 가진다.

 

`abc` 모듈의 `ab stractstaticmethod`와 `ab stractc lassmethod` 데코레이터를 import하면 사용할 수 있다.

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

Data Cleansing  (0) 2020.01.15
matplotlib  (0) 2020.01.12
Pandas (2)  (0) 2020.01.10
Pandas (1)  (0) 2020.01.09
Numpy - Numerical Python  (0) 2020.01.05
Comments