정적 메서드 데코레이터
Coddy Python 여정의 Object Oriented Programming 섹션에 포함된 레슨 — 64개 중 11번째.
@staticmethod 데코레이터는 self나 클래스가 필요하지 않은 메서드를 생성합니다. 이들은 일반 함수처럼 작동하지만 클래스에 속합니다.
다음은 정적 메서드가 있는 클래스의 예시입니다:
class MathHelper:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def is_even(number):
return number % 2 == 0클래스 이름을 사용하여 정적 메서드를 호출합니다:
result = MathHelper.add(5, 3)
print(result)
check = MathHelper.is_even(10)
print(check)객체에서 호출할 수도 있습니다:
helper = MathHelper()
result2 = helper.add(2, 4)
print(result2)출력:
8
True
6정적 메서드는 인스턴스 또는 클래스 데이터에 접근하지 않습니다:
class Calculator:
brand = "Python Calc"
def __init__(self, owner):
self.owner = owner
@staticmethod
def multiply(x, y):
# self.owner 또는 Calculator.brand에 접근할 수 없습니다
return x * y핵심 포인트: 클래스와 관련이 있지만 인스턴스(self) 또는 클래스 데이터에 접근할 필요가 없는 함수가 필요할 때 @staticmethod를 사용하세요. self 매개변수는 필요하지 않습니다.
치트 시트
@staticmethod 데코레이터는 self나 클래스가 필요하지 않은 메서드를 생성합니다. 이들은 일반 함수처럼 작동하지만 클래스에 속해 있습니다.
class MathHelper:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def is_even(number):
return number % 2 == 0클래스 이름을 사용하여 정적 메서드를 호출합니다:
result = MathHelper.add(5, 3)
check = MathHelper.is_even(10)객체에서 호출할 수도 있습니다:
helper = MathHelper()
result2 = helper.add(2, 4)정적 메서드는 인스턴스나 클래스 데이터에 접근하지 않으며, self 매개변수가 필요하지 않습니다.
직접 해보기
이 레슨에는 코드 챌린지가 없습니다.
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.