[Python]class method, instance method, static method

메서드의 종류에 대해 알아보자.

class Car():
    """
    Car class
    Author Jigi
    """

    # 클래스 변수 : 모든 인스턴스가 공유하는 변수
    price_per_raise = 1.0

    def __init__(self, company, details):  # 생성자
        self._company = company
        self._details = details

    def __str__(self):
        return f"str : {self._company} - {self._details}"

    def __repr__(self):
        return f"repr : {self._company} - {self._details}"

    # instance method : self를 파라미터 받는다.
    def detail_info(self):
        print(f'Current ID : {id(self)}')
        print(f'Car detail info : {self._company} {self._details.get("price")}')

    # instance method
    def get_price(self):
        return f'변경 전 가격 => {self._company}, {self._details.get("price")}'

    # instance method
    def get_raised_price(self):
        return f'변경 후 가격 => {self._company}, {self._details.get("price") * Car.price_per_raise}'

    # class method
    @classmethod
    def raise_price(cls, price_rate):
        if price_rate <= 1:
            print('1보다 큰 수를 입력해주세요.')
        cls.price_per_raise = price_rate
        print('가격 인상 성공!!')
        cls.price_per_raise = price_rate

    # static method
    @staticmethod
    def is_bmw(other_car):
        if other_car._company.lower() == 'bmw':
            return True
        return False

car1 = Car("Tesla", {"color": "black", "horespower": 300, "price": 5000})
car2 = Car("Bmw", {"color": "red", "horespower": 400, "price": 6000})


# 전체정보
car1.detail_info()
car2.detail_info()
print()
'''
Current ID : 1958938982048
Car detail info : Tesla 5000
Current ID : 1958938981952
Car detail info : Bmw 6000
'''

# 인스턴스 변수 직접 접근
print(car1._details.get('price'))
print(car2._details.get('price'))
print()
'''
5000
6000
'''

# 인스턴스 메스드로 접근
print(car1.get_price())
print(car2.get_price())

# 클래스 변수 직접 수정
Car.price_per_raise = 1.4

print(car1.get_raised_price())
print(car2.get_raised_price())
print()
'''
변경 전 가격 => Tesla, 5000
변경 전 가격 => Bmw, 6000
변경 후 가격 => Tesla, 7000.0
변경 후 가격 => Bmw, 8400.0
'''

# 클래스 메서드를 통해 비율증가
Car.raise_price(1.5)
print(car1.get_price())
print(car2.get_price())
print(car1.get_raised_price())
print(car2.get_raised_price())
print()
'''
가격 인상 성공!!
변경 전 가격 => Tesla, 5000
변경 전 가격 => Bmw, 6000
변경 후 가격 => Tesla, 7500.0
변경 후 가격 => Bmw, 9000.0
'''

# static method 호출
# 인스턴스 변수를 통해 호출
print(car1.is_bmw(car1))
print(car2.is_bmw(car2))

# 클래스를 통해 호출
print(Car.is_bmw(car1))
print(Car.is_bmw(car2))
'''
False
True
False
True
'''

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다