Python & Django Day7 Class

7 minute read

Fastcampus Python&Django 온라인 강의를 듣고 작성한 Class note입니다.

Class

 1def print_hello(name):
 2	print("Hello ", name)
 3
 4# 함수는 다른 변수명에도 저장할 수 있음
 5print_hello_name = print_hello
 6print_hello_name("Jane")
 7
 8# 함수는 list에도 넣을 수 있음
 9func_list = [print_hello, 1, 2]
10func_list[0]('Jane')
11
12# 함수는 dictionary에도 넣을 수 있음
13func_dict = {
14	'func': print_hello
15}
16
17func_dict['func']('Jane')
 1MY_MONEY = [0]
 2
 3def spend(m):
 4	if MY_MONEY[0] > m:
 5		MY_MONEY[0] -= m
 6		print("{}를 사용했습니다. 남은 잔액 : {}".format(m, MY_MONEY[0]))
 7	else:
 8		print("가지고 있는 돈이 부족합니다.")
 9
10def income(m):
11	MY_MONEY[0] += m
12	print("{}를 벌었습니다. 남은 잔액 : {}".format(m, MY_MONEY[0]))
13
14wallet = {
15	'money': MY_MONEY,
16	'spend': spend
17}
18
19
20
21>>> from file import wallet
22>>> wallet['income'](10000)
2310000를 벌었습니다. 남은 잔액 : 10000
24>>> wallet['spend'](5000)
255000를 사용했습니다. 남은 잔액 : 5000

내 지갑 외에 다른 사람 지갑 만들기 위해서는 위 작업을 동일하게 거쳐야 하기 때문에 매우 힘들다. 그래서 class를 만들어 두면 복제가 빠르다.

class Wallet: pass

1class Wallet(object): # (object) 생략가능. 자동상속 받음.
2	pass
3
4my_wallet = Wallet()
5
6print(my_wallet)

처음 객체가 생성될 때 실행되는 메소드 : init

def ____init(self):

 1class Wallet: 
 2	def __init__(self, name):
 3		self.owner = name
 4	
 5	def print_owner_name(self):
 6		print(self.owner)
 7
 8my_wallet = Wallet('sol')
 9
10print(my_wallet.owner)

클래스가 객체를 만들 때, 객체 자기자신을 의미 하는 것이 self.

지갑 만들기

 1class Wallet: 
 2	money = 0
 3
 4	def __init__(self, name):
 5        print("{}님 환영합니다.".format(name))
 6		self.owner = name
 7	
 8	def print_owner_name(self):
 9		print('owner name is ', self.owner)
10
11	def print_now_money(self):
12		print("현재 잔액은 : ", self.money)
13
14	def spend(self, m):
15		if self.money < m:
16			print("돈이 부족합니다.")
17			self.print_now_money()
18		else:
19			self.money -= m
20			print("{}를 지출했습니다.".format(m))
21			self.print_now_money()
22	def income(self, m):
23		self.money += m
24		print("{}를 입금했습니다.".format(m))
25		self.print_now_money()
26	
27	
28----------------------------------------------------
29
30>>> from file import Wallet
31>>> sol_wallet = Wallet('sol')
32>>> sol_wallet.owner
33'sol'
34>>> sol_wallet.spend(100)
35돈이 부족합니다.
36현재 잔액은 0
37>>> sol_wallet.income(10000)
3810000을 입금했습니다.
39현재 잔액은 10000

Class (2)

상속

1# 부모 클래스의 메소드와 변수들을 가져온다
2
3class Child(Parent):
4	pass
1class ChildWallet(Wallet):
2    pass

python의 모든 클래스는 자동적으로 object를 상속 받는다. issubclass(ChildWallet, Wallet) 를 통해서 상속받았는지 확인 가능하다. (True, False 반환해 줌)

 1class Account(Wallet):
 2    def send_money(self, money, to):
 3        if self.money > money:
 4            to.money += money
 5            self.money -= money
 6            print("{}원을 {}에게 보냈습니다.".format(money, to.owner))
 7            self.print_now_money()
 8
 9-----------------------------------------------------------------
10
11>>> forme file import Account
12>>> sol_a = Account('sol')
13>>> sol_a.income(1000000)
14>>> sol_a.money
15>>> suzy_a = Account('suzy')
16>>> sol_a.send_money(100000, suzy_a)

오버라이드

1class Child(Parent):
2    pass
 1class Account(Wallet):
 2    def __init__(self, name, account_number):
 3        self.account_number = account_number
 4        super().__init__(name)	# 부모 클래스에서 호출
 5    
 6    def __str__(self):
 7        return '{}의 계좌입니다. 계좌번호 :'.format(self.owner, self.account_number)
 8    
 9    def __repr__(self):
10        return '{}의 계좌입니다. 계좌번호 :'.format(self.owner, self.account_number)
11    
12    def __add__(self, another):
13        return self.money + another.money
14    
15    def __call__(self):
16        print("호출되었습니다.")
17    
18    def send_money(self, money, to):
19        if self.money > money:
20            to.money += money
21            self.money -= money
22            print("{}원을 {}에게 보냈습니다.".format(money, to.owner))
23            self.print_now_money()
24
25----------------------------------------------------
26>>> from file import Account
27>>> sol_a = Account('sol', '123-123456')
28>>> sol_a.account_number
29>>> 

super()

부모 호출

Python Special Method

____str()

____call()

____add()(y)

 1class Wallet: 
 2	money = 0
 3
 4	def __init__(self, name):
 5        print("{}님 환영합니다.".format(name))
 6		self.owner = name
 7
 8    #-------------- Special Method --------------#
 9    def __str__(self):
10        return '{}의 지갑입니다.'.format(self.owner)
11    
12    def __repr__(self):
13        return '{}의 지갑입니다.'.format(self.owner)
14	#--------------------------------------------#
15    
16    
17	def print_owner_name(self):
18		print('owner name is ', self.owner)
19
20	def print_now_money(self):
21		print("현재 잔액은 : ", self.money)
22
23	def spend(self, m):
24		if self.money < m:
25			print("돈이 부족합니다.")
26			self.print_now_money()
27		else:
28			self.money -= m
29			print("{}를 지출했습니다ㅇ.".format(m))
30			self.print_now_money()
31	def income(self, m):
32		self.money += m
33		print("{}를 입금했습니다.".format(m))
34		self.print_now_money()