OOP언어에서 보통 인스턴스 변수들은 모두 캡슐화해서 사용한다. 따라서 직접 접근하는 것은 지양된다.
따라서 보통은 getter와 setter를 이용한다.
def get_price(self):
return 'Before Car Price -> company : {}, price : {}'.format(self._company, self._details.get('price'))
def get_price_calc(self):
return 'After Car Price -> company : {}, price : {}'.format(self._company, self._details.get('price') * Car.price_per_raise)
def set_price(self, price):
self._details['price'] = price
print(car1.get_price())
print(car1.get_price_calc())
파이썬에서 클래스 메서드는 다음과 같은 형태로 만든다. @classmethod
라는 데코레이터가 필요하다.
@classmethod
def [클래스메서드명](클래스, ...)
#클래스 메서드
@classmethod
def raise_price(cls, per): #cls변수는 클래스를 인자로 받는다.
if per <= 1:
print('Please Enter 1 or More')
return
cls.price_per_raise = per
print('Succeed! price increased.')
파이썬에서 static메서드는 인자에 self
도, cls
도 받지 않는 메서드이다.
💡 참고로 파이썬 개발자들 중에서도 이 static메서드가 반드시 필요한가에 대해 갑론을박이 이뤄지고 있다고 한다… 솔직히 나도 위의 인스턴스, 클래스 메서드 두개의 구분 말고도 추가의 메서드 기준이 하나 더 있다는게 의문이긴 했다.
스태틱 메서드는 @staticmethod
라는 데코레이터를 이용해 선언한다.