Python/문법
[Python] Static Method (@staticmethod)
comgu
2024. 12. 5. 21:18
반응형
파이썬에서 static method는 클래스의 인스턴스가 아닌 클래스 자체에 속하는 메소드를 말한다.
Static method는 @staticmethod 데코레이터를 사용해 정의되며, 주로 인스턴스나 클래스의 상태에 비의존적인 유틸리티 함수를 위한 것이다.
class MyClass:
@staticmethod
def my_static_method(arg1, arg2):
return f"{arg1}, {arg2}"
Static method의 핵심 특성
- 클래스와 관련된 기능을 위해 사용되지만, 클래스나 인스턴스의 변수들과는 독립적이다.
- 클래스의 인스턴스(self)나 클래스(cls)를 첫번째 인자로 받지 않는다.
- 따라서 클래스 인스턴스의 데이터에 접근할 수 없다(self 객체에 저장된 attribute들에 접근할 수 없음).
- 따라서 클래스의 attribute들 또는 메소드들에 접근할 수 없다(static method 내에서 클래스명을 명시해서 접근할 수는 있음).
- 클래스 자체나 클래스 인스턴스에서 모두 호출할 수 있다.
- static method는 특정 클래스나 인스턴스에 종속되지 않으므로, 접근하는 방식에 상관없이 동일하게 동작한다.
class MathUtils:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def multiply(a, b):
return a * b
# 클래스에서 static method를 호출
print(MathUtils.add(10, 20)) # 출력: 30
print(MathUtils.multiply(5, 4)) # 출력: 20
# 인스턴스에서 static method를 호출
math_utils = MathUtils()
print(math_utils.add(15, 25)) # 출력: 40
Static method는 언제 사용되는가?
- 특정 메소드가 self나 cls를 사용하지 않을 때
- 클래스에 관련된 유틸리티 또는 helper 함수로써
- 클래스와 논리적으로는 관련되있으나 인스턴스의 데이터는 필요로 하지 않는 함수를 구현할 때
왜 Static Method라는 걸 설계했을까?
- 유틸리티 함수 역할: static method는 클래스와 논리적으로 연관된 기능을 제공하지만, 특정 인스턴스나 클래스 상태와는 무관하게 동작할 때 유용하다. 즉 인스턴스나 클래스 상태와 무관하게 항상 일정하게 동작하기 때문에 "정적(static)" 메소드라고 부르는 것이다.
- 코드 가독성: static method를 일반 함수처럼 작성할 수도 있지만, 클래스 안에 정의하면 해당 기능이 클래스와 관련있다는 점을 명확히 보여줄 수 있다.
class Calculator:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def subtract(a, b):
return a - b
# 클래스 상태와 무관하게 일정하게 동작
print(Calculator.add(10, 5)) # Output: 15
print(Calculator.subtract(10, 5)) # Output: 5
# 인스턴스를 생성해도 동일
calc = Calculator()
print(calc.add(20, 10)) # Output: 30
print(calc.subtract(20, 10)) # Output: 10
클래스(Calculator)를 통해 호출하든, 인스턴스(calc)를 통해 호출하든 static method의 결과는 항상 동일하다.
반응형