메서드의 종류
- 인스턴스 메서드
파라미터 self => 객체를 이용하여 메서드 호출
- 클래스 메서드
파라미터 cls => 클래스를 이용하여 메서드 호출(객체로 생성된 초기 변수값을 모두 수정)
메서드 위에 @classmethod를 적어준다.
- 스태틱 메서드
파라미터 X => 객체를 선언하지 않고 메서드 호출
메서드 위에 @staticmathod를 적어준다.
다음과 같은 코드를 보자!
class Account:
interest = 1.01 # 이자율 1%
def __init__(self, asset = 10000):
self.asset = asset
def deposit(self, amount):
self.asset += amount
def withdraw(self, amount):
if self.asset >= amount:
self.asset -= amount
else:
print('total asset', self.asset)
def add_interest(self):
self.asset = int(self.asset * self.interest)
print('total asset', self.asset)
def change_interest(self, interest):
if interest < 1.10:
self.interest = interest
else:
print('이자율을 10% 미만으로 설정해주세요.') # 인스턴스 메서드
@classmethod
def cls_change_interest(cls, interest):
if interest < 1.10:
cls.interest = interest
else:
print('이자율을 10% 미만으로 설정해주세요.') # 클래스 메서드
@staticmethod
def interest_grade(interest):
if interest > 1.05:
print('high interest')
elif interest > 1.02:
print('middle interest')
else:
print('low interest') # 스태틱 메서드
계좌에서 돈을 입금하고 인출하고...
이자도 주고...
이자율이 높은지 낮은지 확인하고...
그런 코드이다.
일단 계좌1, 2, 3 객체를 생성한 뒤....
그리고 나서 각 객체의 자산과 이자율을 확인해보면...
account1 = Account(10000)
account2 = Account(20000)
account3 = Account(30000)
account1.asset, account2.asset, account3.asset,\
account1.interest, account2.interest, account3.interest
이렇게 정보가 나온다.
먼저, 인스턴스 메서드인 change_interest()를 account1객체에 사용 한뒤...
자산과 이자율을 확인해 보면...
account1.change_interest(1.09)
account1.asset, account2.asset, account3.asset,\
account1.interest, account2.interest, account3.interest
객체 1의 이자율만 바뀐 것을 확인할 수 있다!
이번엔 클래스 메서드인 cls_change_interest()를 사용해보자!
Account.cls_change_interest(1.04) # 클래스메서드라서 클래스에 사용
account1.asset, account2.asset, account3.asset,\
account1.interest, account2.interest, account3.interest
이렇게 클래스 메서드로 클래스로부터 만들어진 객체의 이자율을 1.04로 변경했다.
실행해서 이자율을 확인해 보면...
위와 같이 인스턴스 메서드로 이자율을 고쳐준 account1빼고 모두 이자율이 바뀐 것을 확인할 수 있다.
마지막으로 스태틱 메서드인 interest_grade()를 사용해보자!
Account.interest_grade(account1.interest)
Account.interest_grade(account2.interest)
이렇게 account1.interest와 account2.interest를 확인해 보면...
계좌1의 이자율은 높고(1.09), 계좌2의 이자율은 중간(1.04)임을 확인할 수 있다.
메서드의 맹글링
코드의 유지보수가 쉬워진다.
아래와 같이 __show_asset이라는 메서드를 새로 작성해서...
class Account:
interest = 1.01 # 이자율 1%
def __init__(self, asset = 10000):
self.asset = asset
def __show_asset(self):
print('total asset', self.asset) # 맹글링
def deposit(self, amount):
self.asset += amount
def withdraw(self, amount):
if self.asset >= amount:
self.asset -= amount
else:
self.__show_asset() # 맹글링
def add_interest(self):
self.asset = int(self.asset * self.interest)
self.__show_asset() # 맹글링
def change_interest(self, interest):
if interest < 1.10:
self.interest = interest
else:
print('이자율을 10% 미만으로 설정해주세요.') # 인스턴스 메서드
@classmethod
def cls_change_interest(cls, interest):
if interest < 1.10:
cls.interest = interest
else:
print('이자율을 10% 미만으로 설정해주세요.')
@staticmethod
def interest_grade(interest):
if interest > 1.05:
print('high interest')
elif interest > 1.02:
print('middle interest')
else:
print('low interest')
겹치는 부분을 줄여줄 수 있다!
이번 시간에는 메서드의 종류와 메서드의 맹글링을 알아보았습니다...
메서드가 3가진데...
공부하다가 4가지가 없어질것같네여...ㅎㄷㄷ
그럼... 이만...
'멋쟁이사자처럼 AI스쿨' 카테고리의 다른 글
입력과 출력(파이썬 강의 Day5) (0) | 2023.01.06 |
---|---|
클래스 설계(파이썬 강의 Day5) (0) | 2023.01.06 |
getter, setter, mangling(파이썬 강의 Day5) (2) | 2023.01.06 |
클래스로 마린과 메딕 구현하기(파이썬 강의 Day4 Quiz) (0) | 2023.01.06 |
매출늘려버리기!(파이썬 강의 Day4) (0) | 2023.01.05 |
댓글