@staticmethod @classmethod
목차
1. class 멤버변수
2. static 멤버함수 #staticmethod
3. class 멤버함수 #@classmethod
클래스 멤버변수
클래스 멤버함수(=static 멤버함수) #@staticmethod
인스턴스 멤버변수
인스턴스 멤버함수
class 멤버변수
개체에서도 접근 가능
static 멤버함수
self를 인자로 받지 않음
class 멤버함수
cls를 첫번째 인자로 받음
클래스를 인자로 전달 가능
class Animal:
# 클래스 변수
total_animals = 0
def __init__(self, species, sound):
# 인스턴스 변수
self.species = species
self.sound = sound
# 클래스 변수 업데이트
Animal.total_animals += 1
# Animal 클래스의 인스턴스들 생성
lion = Animal("Lion", "Roar")
dog = Animal("Dog", "Bark")
cat = Animal("Cat", "Meow")
# 클래스 변수에 접근
print("총 동물 수:", Animal.total_animals) # 출력: 총 동물 수: 3
필요성 : 개체와 아무 상관없는 함수를 실행시킬 때. 굳이 개체를 생성하지 않아도 실행가능한 함수
아래 예제에서는 개체를 생성시키지 않고 덧셈 연산을 하고 있다.
class MathOperations:
@staticmethod
def add(x, y): # 매개변수에 self가 없음
return x + y
# 정적 메서드 사용
result = MathOperations.add(5, 3) #개체 생성 안 하고, 클래스에서 곧바로 멤버함수 실행
print("덧셈 결과:", result) # 출력: 덧셈 결과: 8
class MyClass:
def __init__(self, value):
self.value = value
@classmethod
def create_instance(cls, value):
instance = cls(value)
return instance
new_instance = MyClass.create_instance(1) # 클래스 메서드를 사용하여 객체 생성
print(new_instance.value)
열혈 파이썬 중급편(윤성우)