상세 컨텐츠

본문 제목

Class와 method 활용 (5) - Static method

개발/python-심화(Advanced)

by Matthew0633 2022. 4. 4. 23:26

본문

Static Method

업무를 할 때 static method를 정의하는 기준이 굉장히 애매해서 여러 자료를 검색했지만 명쾌한 답을 얻지 못했던 기억이 있다. 그런데 실제로 static method는 stack overflow 등에도 의견이 분분할 정도로 활용 기준에 정답이 없다고 강사님께서 말씀하셨다. 다만 static method를 통해 Class 내에서 Class method와 instance method 사이의 유연성을 가진 method 정의를 지원하기에 내가 필요하다고 판단되면 사용하면 된다!

Why :
Class 와 관련이 있어, 외부에 function으로 정의하기는 적절하지 않고, method 인자로 instance, Class 를 모두 구별 없이 받아 사용하고 싶은 기능을 정의할 때, static method를 활용한다

How:
static method를 접근할 때는 Car.method() 또는 c1.method() 와 같이 Class 와instance로 모두 가능하다

class Car(object):
    
    # Class Variable
    price_per_raise = 1.0

    def __init__(self, company, details):
        self._company = company
        self._details = details

    @staticmethod
    def is_bmw(inst): # 인자로 instance를 받도록 정의
        if inst._company == 'Bmw':
            return 'OK! This car is {}.'.format(inst._company)
        return 'Sorry. This car is not Bmw.'
    
car1 = Car('Bmw', {'color' : 'Black', 'horsepower': 270, 'price': 5000})

static method 를 정의할 때는, decorator를 활용하여 @staticmethod 를 method 상단에 정의한다. 필수적으로 clsself 를 인자로 받아야하는 것은 아니다.

<Reference>
우리를 위한 프로그래밍 : 파이썬 중급 (인프런)

관련글 더보기

댓글 영역