본문 바로가기
Programming/python

[python] 정적메서드 @classmethod @staticmethod

by Finn# 2023. 7. 11.
728x90

method?

 Class 내에서 객체가 구현할 특정한 기능을 함수 형태로 정의하는 것을 method라고 받아들일 때, 해당 method가 절자지향적인 역학을 수행할 때 해당 역학을 이용하여 별도의 class instance 생성없이 메모리에 올라와있는 해당 method를 사용할 수 있을 때, 이를 staticmethod라고 한다. instance method와의 차이는 비교하고자 하는 method가 어떻게 메모리에 올라오는 지의 차이에 있다.

 

 instance method의 경우에는 class의 instance가 정의되면서 해당 instance를 컴파일하는 과정에서 memory의 static한 공간에 method의 주소가 호출되는 형태로 이해하면 좋을 것 같다. 반면에 staticmethod 경우는 별도 instance 정의없이 class를 참조하여 컴파일하는 과정에서 static한 공간에 method가 호출되는 형태이다.

 

static method를 사용하는 이유는 필요에 의해 class를 정의하고나서 여러 객체들을 생성할 때, 동일한 메서드가 반복하여 생성할 때 같은 클래스를 통해 생성된 객체들간 같은 코드를 사용하는 것을 보장하기 위해 사용된다.

 

 


python에서 정적 메서드?

 흔히 우리가 python에서 사용하는 정적 메서드는 @classmethod와 @staticmethod가 있다.

@staticmethod는 일반적으로 위에서 설명한 것처럼 정적메소드를 구현하기 위해서 python에서 사용하는 구문이다. 이 코드를 사용하면 부모 class에서 정의된 method의 내용이 실행된다.

 

 반면 @classmethod의 경우에는 부모 class에서 정의된 Staticmethod를 사용하나, 새롭게 정의한 자식 클래스의 변수들을 반영한다. 상속된 아래 코드를 통해 @staticmethod와 @classmethod의 결과를 비교해보면 무슨 말인지 이해가 갈 것이다.

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 아빠

개념 정리

 일반적인 메소드와 정의방식이 다르다는 점이 이해가 안간다면, 다음 코드를 참고해보면 좋다.

class example():
	
    def method1():
    	return example()
    
    @staticmethod
    def method2():
    	return example()

여기서 method1을 사용하기 위해선 example() 이란 instance를 생성하고 method1을 사용하면 된다. 이 경우가 class의 instance를 생성하여 method를 사용하는 instance method의 경우이다.

example1 = example()
example1.method1()

하지만 method2의 경우에는 우리가 @staticmethod로 설정한 경우에는 별도의 instance 생성없이 example을 참조하여 method2를 호출할 수 있다.

example2 = example.method2()

인스타 주소 🎗

https://www.instagram.com/f.inn_sharp/

반응형