무냐의 개발일지
파이썬 클래스, 객체, 계좌만들기 실습 본문
(점프 투 파이썬)
(파이썬 300제)
# 클래스는 타입을 만드는 도구디
class Calculator:
def __init__(self):
self.result=0
def add(self, num):
self.result += num
return self.result
cal1 = Calculator()
cal2 = Calculator()
print(cal1.add(3))
print(cal1.add(5))
print(cal2.add(6))
print(cal2.add(8))
결과 :
3
8
6
14
Calculator : 클래스
cal1, cal2 : 객체
클래스 안에 구현된 함수는 다른 말로 메서드(method)라고 부른다.
setdata 메서드에는 self, first, second 총 3개의 매개변수가 필요한데 실제로는 a.setdata(4, 2)처럼 2개의 값만 전달했다. 왜 그럴까? a.setdata(4, 2)처럼 호출하면 setdata 메서드의 첫 번째 매개변수 self에는 setdata 메서드를 호출한 객체 a가 자동으로 전달되기 때문이다.
객체에 first, second와 같은 초깃값을 설정해야 할 필요가 있을 때는 setdata와 같은 메서드를 호출하여 초깃값을 설정하기보다 생성자를 구현하는 것이 안전한 방법이다.
생성자(constructor)란 객체가 생성될 때 자동으로 호출되는 메서드를 의미한다. 파이썬 메서드명으로 __init__를 사용하면 이 메서드는 생성자가 된다.
* __init__ : 객체가 생성되는 시점에 자동으로 호출된다
# 계산기 만들기
class Fourcal:
def __init__(self, first, second):
self.first = first
self.second = second
# def setdata(self, first, second):
# self.first = first
# self.second = second
def add(self):
result = self.first + self.second
return result
def sub(self):
result = self.first - self.second
return result
def mul(self):
result = self.first * self.second
return result
def div(self):
result = self.first / self.second
return result
a = Fourcal(4,2)
print(type(a))
# a.setdata(4,2)
print(a.first)
print(a.second)
print(a.add())
print(a.mul())
print(a.div())
print(a.sub())
# 클래스의 상속 : 상속을 하면, 그 모든 기능을 사용할 수 있다
# 보통 상속은 기존 클래스를 변경하지 않고 기능을 추가하거나 기존 기능을 변경하려고 할 때 사용한다.
class MoreFourCal(Fourcal):
def pow(self):
result = self.first ** self.second
return result
a = MoreFourCal(10,5)
print(a.add())
print(a.sub())
print(a.div())
print(a.mul())
print(a.pow())
| 은행계좌 만들기 실습 클래스
import random
class Account:
account_count = 0
def __init__(self, name, balance):
self.num_deposit = 0
self.deposit_history = []
self.withdraw_history = []
self.name = name
self.balance = balance
self.bank = 'SC은행'
num1 = random.randint(0,999)
num2 = random.randint(0,99)
num3 = random.randint(0,999999)
num1 = str(num1).zfill(3)
num2 = str(num2).zfill(2)
num3 = str(num3).zfill(6)
self.account = num1+'-'+num2+'-'+num3
Account.account_count += 1
def get_account_num(cls):
print(cls.account_count)
def deposit(self, amount):
if amount >= 1:
self.deposit_history.append('+ {:,}원이 입금되었습니다'.format(amount))
self.balance += amount
self.num_deposit += 1
if self.num_deposit % 5 == 0:
self.balance = self.balance * 1.01
def withdraw(self, amount):
if self.balance > amount:
self.balance -= amount
self.withdraw_history.append('- {:,}원이 출금되었습니다'.format(amount))
def display_info(self):
print('은행이름: {} \n예금주: {} \n계좌번호: {} \n잔고: {:,}원 \n입금내역 : {} \n출금내역: {}'.format(self.bank, self.name, self.account, self.balance, self.deposit_history, self.withdraw_history))
kim = Account('김민수', 1005000)
print(kim.name)
print(kim.balance)
print(kim.bank)
print(kim.account)
print(Account.account_count)
kim.get_account_num()
kim.deposit(23235)
# kim.withdraw(50000)
print(kim.balance)
p = Account("파이썬", 10000)
p.display_info()
p.deposit(100)
p.deposit(100)
p.deposit(100)
p.deposit(100)
p.deposit(100)
print(p.balance)
data = []
o = Account('오징어', 10000000)
l = Account('라면', 5030702000)
s = Account('소라게', 295930)
o.deposit(3000)
l.withdraw(50)
s.deposit(320523)
s.withdraw(325)
l.deposit(235320)
o.deposit(32)
o.deposit(32530)
data.append(o)
data.append(l)
data.append(s)
print(data)
for i in data:
if i.balance >= 1000000:
i.display_info()
뿌듯 !!!
'데싸 추가 독학' 카테고리의 다른 글
[자료구조] 배열, 연결리스트 시간복잡도 비교 (0) | 2024.04.11 |
---|---|
[자료구조] 파이썬으로 계산기 만들기 (Stack) (0) | 2024.04.09 |
ARIMA 모델에서 가장 중요한 정상성 확인 | ADFuller test에 대하여 (0) | 2024.02.29 |
[머신러닝] 머신러닝에 사용되는 라이브러리 순서!! (0) | 2024.02.19 |
[데이터 과학을 위한 통계]#1 EDA 탐색적 데이터분석 (0) | 2024.02.18 |