[Python] Class - Method

^_^·2022년 5월 31일
0

Python

목록 보기
2/9
post-thumbnail

Class - Method

이전 포스팅에서 기본적인 클래스의 사용법과 self를 인자로 받는 인스턴스 메소드를 알아봤다. 이번에는 클래스 내에서 사용할수 있는 다른 두가지 메소드를 공부했다.

classmethod

클래스 메소드는 데코레이터 @classmethod를 class내에 입력해 사용하고 인스턴스 메소드가 첫번째 파라미터로 자신의 인스턴스를 "self"로 전달하는 것과는 달리 "cls"라는 파라미터로 자신의 클래스를 전달한다. 이전 포스팅에서 사용한 코드에 클래스 메소드를 추가해 확인해 보자.

@classmethod같이 @를 사용하는 표식을 데코레이터(decorator)라고 한다.


class Laptop():
    price_per_raise = 1.0

    def __init__(self, laptop, details):
        self._laptop = laptop
        self._details = details

    def __str__(self):
        return '{} - {}'.format(self._laptop, self._details)

    # Instance method
    def get_price(self):
        return 'Before Car Price -> laptop : {}, price : {}'.format(self._laptop, self._details.get('price'))

    # Instance method
    def get_price_culc(self):
        return 'After Car Price -> laptop : {}, price : {}'.format(self._laptop, self._details.get('price')* Laptop.price_per_raise)

    # Class method
    @classmethod
    def raise_price(cls, per):
        if per <= 1:
            print('Please Enter 1 Or More')
            return
        cls.price_per_raise = per
        print('Succeed! price increased')

# 가격정보(인상 전)
print(laptop1.get_price())
print(laptop2.get_price())
print(laptop3.get_price())

# 클래스 메소드 사용 
Laptop.raise_price(1.6)

# 가격정보(인상 후)
print(laptop1.get_price_culc())
print(laptop2.get_price_culc())
print(laptop3.get_price_culc())

# 출력

Before Car Price -> laptop : Gram, price : 1700000
Before Car Price -> laptop : Macbook, price : 1500000
Before Car Price -> laptop : Thinkpad, price : 1400000
Succeed! price increased
After Car Price -> laptop : Gram, price : 2720000.0
After Car Price -> laptop : Macbook, price : 2400000.0
After Car Price -> laptop : Thinkpad, price : 2240000.0

staticmethod

스태틱 메소드는 데코레이터 @staticmethod를 class내에 입력해 사용하고 self나 cls를 인자로 받지 않아도 되는 함수이다.


class Laptop():
    price_per_raise = 1.0

    def __init__(self, laptop, details):
        self._laptop = laptop
        self._details = details

    def __str__(self):
        return '{} - {}'.format(self._laptop, self._details)

    # Instance method
    def get_price(self):
        return 'Before Car Price -> laptop : {}, price : {}'.format(self._laptop, self._details.get('price'))

    # Instance method
    def get_price_culc(self):
        return 'After Car Price -> laptop : {}, price : {}'.format(self._laptop, self._details.get('price')* Laptop.price_per_raise)

    # Class method
    @classmethod
    def raise_price(cls, per):
        if per <= 1:
            print('Please Enter 1 Or More')
            return
        cls.price_per_raise = per
        print('Succeed! price increased')

    # Static method
    @staticmethod
    def is_Macbook(inst):
        if inst._laptop == 'Macbook':
            return 'OK! This laptop is {}'.format(inst._laptop)
        return 'Sorry. This laptop is not Macbook.'


# 제조사 정보 인스턴스 호출(staticmethod)
print(laptop1.is_bmw(laptop1))
print(laptop2.is_bmw(laptop2))
print(laptop3.is_bmw(laptop3))
# 제조사 정보 클래스 호출(staticmethod)
print(Laptop.is_bmw(laptop1))
print(Laptop.is_bmw(laptop2))
print(Laptop.is_bmw(laptop3))

# 출력 결과
Sorry. This laptop is not Macbook.
OK! This laptop is Macbook
Sorry. This laptop is not Macbook.
Sorry. This laptop is not Macbook.
OK! This laptop is Macbook
Sorry. This laptop is not Macbook.

스태틱 메소드로 Macbook노트북이 맞는지 확인하는 스태틱 메소드 is_Macbook을 추가했다. 스태틱 메소드는 인스턴스와 클래스 모두 호출할 수 있다.

0개의 댓글