Nubes et Stella

[Python] @classmethod와 @staticmethod 본문

Programming/Python

[Python] @classmethod와 @staticmethod

SeongYeong Han 2023. 9. 21. 21:33

01. 클래스메서드(classmethod)란?

클래스를 공부하면서 클래스메서드(@classmethos)에 대해서 알게되었다. 

클래스메서드는 클래스 내에서 선언된 메서드 중에서 첫번째 매개변수로 "cls"받고 함수명위에 @classmethod를 표기한다.

 

매개변수로 "cls"를 받기 때문에 클래스 내부의 클래스 변수와 다른 클래스 메서드에 접근할 수 있습니다.

아래는 클래스변수를 사용한 예이다.

 

여기서 클래스메서드 "get_user_count"는 클래스변수 "user_count"에 접근하여 생성된 사용자 수를 출력해준다.

class User:
    user_count = 0

    def __init__(self, username):
        self.username = username
        User.user_count += 1

    @classmethod
    def get_user_count(cls):
        return cls.user_count

# 사용자 생성
user1 = User("Alice")
user2 = User("Bob")

# 클래스 메서드 호출하여 사용자 수 조회
user_count = User.get_user_count()
print(f"총 사용자 수: {user_count}")
총 사용자 수: 2

 

 

02. 스택틱메서드(staticmethod)란?

스태틱메서드는 클래스안에 선언은 되어있으나, 독립적으로 사용되는 메서드이다. 때문에 클래스 변수에는 접근이 가능하나, 생성자를 포함한 인스턴스 변수에는 접근이 불가능하다.

 

아래의 코드는 화씨와 섭씨를 각각 변환해주는 스태틱메서드를 구현한 것이다.

class TemperatureConverter:
    @staticmethod
    def celsius_to_fahrenheit(celsius):
        return (celsius * 9/5) + 32

    @staticmethod
    def fahrenheit_to_celsius(fahrenheit):
        return (fahrenheit - 32) * 5/9

# 섭씨를 화씨로 변환
celsius_temp = 30
fahrenheit_temp = TemperatureConverter.celsius_to_fahrenheit(celsius_temp)
print(f"{celsius_temp}°C는 {fahrenheit_temp}°F 입니다.")

# 화씨를 섭씨로 변환
fahrenheit_temp = 86
celsius_temp = TemperatureConverter.fahrenheit_to_celsius(fahrenheit_temp)
print(f"{fahrenheit_temp}°F는 {celsius_temp}°C 입니다.")
30°C는 86.0°F 입니다.
86°F는 30.0°C 입니다.

 

 

03. @classmethod와 @staticmethod 차이?

위의 내용만 봐서는 정확한 차이를 파악하기가 솔직히 힘들다.... 여기서 좀 더 명확한 차이를 확인하기 위해 다른 블로그의 글을 참고하였다.

 

그 글에서 말하는 것은 바로 클래스 상속에서 발생하는 차이이다!! . 백문이 불여일견!! 아래의 코드를 확인해 보자

class Person:
    default= "아빠"

     def __init__(self):
        self.data = self.default

    @classmethod
    def class_person(cls):
        return cls()

    @staticmethod
    def static_person():
        return Person()

class WhatPerson(Person):
    default = "엄마"
    
person1 = WhatPerson.class_person()    # return 엄마
person2 = WhatPerson.static_person()   # return 아빠

위와 같이 @staticmethod인 경우에는 부모 클래스의 속성 값을 가져오지만, @classmethod의 경우 cls인자를 활용하여 클래스의 클래스 속성을 가져온다.

 

 

04. 만약 둘 다 표기하지 않았을 때는??

@classmethod와 @staticmethod 둘다 표기하지 않을 경우 일반적인 인스턴스 메서드로 우리가 흔히 아는 self매개변수를 받는 메서드이다.

 

아래의 코드는 인스턴스 메서드로 self 매개변수를 통해 인스턴스에 접근이 가능하다.

class MyClass:
    def instance_method(self):
        print("인스턴스 메서드 호출")

# 클래스 인스턴스 생성
obj = MyClass()

# 인스턴스 메서드 호출
obj.instance_method()

 

 

 

'Programming > Python' 카테고리의 다른 글

[Python] range()와 xrange()의 차이  (0) 2023.10.07
[Python] 클래스 생성자(__init__)  (0) 2023.09.04