Python Class

TonyHan·2020년 7월 29일
0

Python

목록 보기
1/6
post-thumbnail

Python Class


1. Magic(Special) Method

"test".__eq__("test")

 class Txt:
    def __init__(self,txt):
        self.txt=txt
        
    def __eq__(self,txt_obj):
        return self.txt.lower() == txt_obj.txt.lower()
  • #출력 (그냥 객체만 입력하였을 때 사용되는 것)
  • #repr 이라는 표현은 represent의 약자인가 보다
    def __repr__(self): 
    	return "Txt(txt={})".format(self.txt)
  • #주의 사항 : 출력은 반드시 str 이어야만함. int 형 이라고 하더라도 str로 변환
  • #출력 (print 를 사용하여 객체를 출력할때 사용되는 것)
    def __str__(self):
        return self.txt
  • #주의 사항 : 출력은 반드시 str 이어야만함. int 형 이라고 하더라도 str로 변환
t1 = Txt("python")
t2 = Txt("Python")
t3 = t1
  • 이와 같이 ==도 사실은 객체 내부에 기본으로 설정된 eq magic method 에 의해 실행되는 것
t1 == t2, t1==t3, t2==t3
(False, True, False)
  • 여기에서는 repr 이 실행됨
t1
Txt(txt=python)


print(t1)
python

1-1 Class quiz

  • 계좌 클래스 만들기
  • 변수 : 자산(asset), 이자율(interest)
  • 함수 : 인출(draw), 입금(insert), 이자추가(add_interest)
  • 인출시 자산이상의 돈을 인출할 수 없습니다.
class Account:
    def __init__(self,asset = 0,interest = 1.05):
        self.asset = asset
        self.interest = interest
    
    def draw(self,money):
        if(self.asset>=money):
            self.asset-=money
            print("{}원이 인출되었습니다.".format(money))
        else:
            print("잔고는 {}원이고, {}원이 부족합니다.".format(self.asset,money-self.asset))
            
    def insert(self,money):
        self.asset+=money
        print("{}원이 입금되어 잔고{}원이 남았습니다.".format(money,self.asset))
        
    def add_interest(self):
        print("이자 {}원이 입금 되었습니다.".format(self.asset*self.interest-self.asset))
        self.asset*=self.interest

    def __repr__(self):
        return "Account(asset:{}, interest:{})".format(self.asset,self.interest)
account1 = Account(10000)

account1
>Account(asset:10000, interest:1.05)

account1.draw(12000)
>잔고는 10000원이고, 2000원이 부족합니다.

account1.insert(5000)
>5000원이 입금되어 잔고15000원이 남았습니다.

account1
>Account(asset:15000, interest:1.05)

account1.add_interest()
>이자 750.0원이 입금 되었습니다.

account1
>Account(asset:15750.0, interest:1.05)
profile
신촌거지출신개발자(시리즈 부분에 목차가 나옵니다.)

0개의 댓글