본문 바로가기
카테고리 없음

파이썬 Keyword: @staticmethod vs @classmethod, 쉬운 동작 원리와 샘플코드

by 뷰티풀스택 2023. 7. 3.
반응형

@staticmethod와 @classmethod는 둘 다 파이썬 클래스 내에서 사용되는 특수한 데코레이터(decorator)입니다. 이 데코레이터들을 사용하면 클래스 안에서 정의된 메소드를 클래스와의 관계없이 호출할 수 있습니다.

 

@staticmethod:

@staticmethod 데코레이터는 클래스의 인스턴스와는 상관없이 호출되는 정적 메소드(static method)를 정의합니다. 즉, 인스턴스 멤버에 접근하는 데 필요한 self 매개변수가 필요하지 않습니다. 주로 클래스의 유틸리티 메소드를 정의하거나, 클래스의 특정 상태에 의존하지 않는 독립적인 작업을 수행하기 위해 사용됩니다. 이 메소드는 클래스 또는 인스턴스에 대해 액세스할 수 있는 다른 멤버 변수에는 액세스할 수 없으므로(클래스에 대해 선언되었지만, 인스턴스 속성으로도 호출이 가능할 수 있음에 유의), 외부 종속성이 없는 모듈화된 기능을 구현하는 데 적합합니다.

 

예를 들어보겠습니다:

 

```python

class MyClass:

    @staticmethod

    def my_static_method():

        # 클래스의 상태에 의존하지 않는 일반 로직

        print("This is a static method")

 

# 클래스의 인스턴스를 생성하지 않고 정적 메소드 호출

MyClass.my_static_method()

```

 

@classmethod:

@classmethod 데코레이터는 클래스 메소드(class method)를 정의합니다. 이 때 메소드는 첫 번째 매개변수로 클래스 자체를 나타내는 cls를 가집니다. 클래스 메소드는 인스턴스와 관련된 동작이 아닌, 클래스 전반적인 동작을 정의하기 위해 사용됩니다. 클래스 메소드는 클래스 변수에 접근하고, 클래스의 인스턴스를 생성하고, 클래스의 다른 메소드에 액세스하는 데 사용됩니다.

 

예를 들어보겠습니다:

 

```python

class MyClass:

    x = 0  # 클래스 변수

 

    @classmethod

    def my_class_method(cls):

        # 클래스 변수에 접근

        cls.x += 1

        # 클래스 인스턴스 생성

        instance = cls()

        # 인스턴스 메소드 호출

        instance.my_instance_method()

 

    def my_instance_method(self):

        print("This is an instance method")

 

# 클래스 메소드 호출

MyClass.my_class_method()

```

 

이상은 @staticmethod와 @classmethod에 대한 설명과 간단한 예제입니다. 자세한 내용은 파이썬 공식 문서를 참조하시기 바랍니다.

 

참고: https://docs.python.org/3/library/functions.html#staticmethod 

 

Built-in Functions

The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.,,,, Built-in Functions,,, A, abs(), aiter(), all(), a...

docs.python.org

        https://docs.python.org/3/library/functions.html#classmethod

반응형

댓글