class method & static method 차이

김윤하·2022년 9월 13일

Python

목록 보기
3/11

1. static method

  • 자식 class 에서 call 가능
  • 클래스 변수에 접근 가능
  • 인스턴스 메소드 변수에 접근 불가능

2. class method

  • 부모 클래스에서 정의된 클래스 변수와 클래스 메소드는 자식 클래스에서도 선언이 가능
  • 클래스 변수에 접근이 가능
  • 생성자 함수 포함 인스턴스 메소드 변수에 접근이 불가능

3. 비교 코드

class P:
    static_name = 'static_부모'
    class_name = 'class_부모'

    @staticmethod
    def change_s_name(temp):
        P.static_name = temp

    @classmethod
    def change_c_name(cls, temp):
        cls.class_name = temp


class C(P):
    pass


parent = P()
child = C()

print(parent.static_name, child.static_name)
child.change_s_name('static_자식')
print('↓ static method 이름 변경 후')
print(parent.static_name, child.static_name)

print('='*20)

print(parent.class_name, child.class_name)
child.change_c_name('class_자식')
print('↓ class method 이름 변경 후')
print(parent.class_name, child.class_name)

>>> output
static_부모 static_부모
↓ static method 이름 변경 후
static_자식 static_자식
====================
class_부모 class_부모
↓ class method 이름 변경 후
class_부모 class_자식

마치면서

자바에서는 이 두 가지 개념이 동일하게 사용한다. 왜냐하면 정적 메서드에서도 클래스 이름을 통해 자유롭게 클래스에 접근할 수 있기 때문입니다. 파이썬에서도 상속 빼고는 기능적으로는 큰 차이가 없지만 클래스에 접근이 필요할 때는 classmethod, 접근이 필요없을 때는 staticmethod를 사용하도록 되어 있습니다.

profile
data engineer

0개의 댓글