1 2 3 4 user_datas = [ {"user" :"test" , "pw" :"1234" , "count" :0 }, {"user" :"python" , "pw" :"5678" , "count" :0 }, ]
1 2 3 4 5 ls = ["a" , "b" , "c" ] print(list (range (len (ls)))) print(list (zip (range (len (ls)), ls))) for idx, data in list (zip (range (len (ls)), ls)): print(idx, data)
[0, 1, 2]
[(0, 'a'), (1, 'b'), (2, 'c')]
0 a
1 b
2 c
1 list (enumerate (user_datas))
[(0, {'user': 'test', 'pw': '1234', 'count': 0}),
(1, {'user': 'python', 'pw': '5678', 'count': 1})]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 def need_login (func ): def wrapper (*args, **kwargs ): user, pw = tuple (input ("insert user pw :" ).split(" " )) for idx, user_data in enumerate (user_datas): if user_data["user" ] == user and user_data["pw" ] == pw: user_datas[idx]["count" ] += 1 return func(*args, **kwargs) return "wrong login data!" return wrapper
1 2 3 @need_login def plus (num1, num2 ): return num1 + num2
insert user pw :test 1234
3
[{'user': 'test', 'pw': '1234', 'count': 1},
{'user': 'python', 'pw': '5678', 'count': 2}]
1 2 3 4 5 6 7 8 9 10 11 12 13 class Marine : def __init__ (self, health=40 , attack_pow=5 ): self.health = health self.attack_pow = attack_pow def attack (self, unit ): unit.health -= self.attack_pow print(unit.health) if unit.health <= 0 : unit.health = 0 print("사망" ) pass
1 marine_1.attack(marine_2)
사망
1 marine_1.health, marine_2.health
(40, 0)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Medic : def __init__ (self, health = 40 , heal_pow=6 ): self.health = health self.heal_pow = heal_pow def heal (self, unit ): if unit.health > 0 : unit.health += self.heal_pow if unit.health >=40 : unit.health = 40 else : print("이미 사망" )
1 marine_1.attack(marine_2)
사망
1 marine_1.health, marine_2.health
(40, 0)
이미 사망
1 marine_3 = Marine(attack_pow=25 )
1 marine_3.attack(marine_1)
사망
1. 상속
클래스의 기능을 가져다가 기능을 수정하거나 추가할때 사용하는 방법
1 2 3 4 5 6 7 class Calculator : def __init__ (self, num1, num2 ): self.num1 = num1 self.num2 = num2 def plus (self ): return self.num1 + self.num2
1 2 calc = Calculator(1 , 2 ) calc.plus()
3
1 2 3 4 5 6 7 8 9 10 class Calculator2 : def __init__ (self, num1, num2 ): self.num1 = num1 self.num2 = num2 def plus (self ): return self.num1 + self.num2 def minus (self ): return self.num1 - self.num2
1 calc2 = Calculator2(1 , 2 )
-1
1 calc2.minus(), calc2.plus()
(-1, 3)
1 2 3 4 class Calculator3 (Calculator ): def minus (self ): return self.num1 - self.num2
1 calc3 = Calculator3(1 , 2 )
1 calc3.plus(), calc3.minus()
(3, -1)
1 2 3 4 5 class Calculator4 (Calculator3 ): def plus (self ): return self.num1**2 + self.num2**2
1 calc4 = Calculator4(1 , 2 )
5
1 2 3 class iPhon1 : def calling (self ): print("calling" )
1 2 3 class iPhon2 (iPhon1 ): def send_msg (self ): print("send_msg" )
1 2 3 class iPhon3 (iPhon2 ): def internet (self ): print("internet" )
1 iphon3.calling(), iphon3.send_msg(), iphon3.internet()
calling
send_msg
internet
(None, None, None)
1 2 3 class Galuxy : def show_img (self ): print("show_img" )
1 2 3 class DssPhone (iPhon3, Galuxy ): def camera (self ): print("camera" )
1 [func for func in dir (dss_phone) if func[:2 ] != '__' ]
['calling', 'camera', 'internet', 'send_msg', 'show_img']
2. super
부모 클래스에서 사용된 함수의 코드를 가져다가 자식 클래스의 함수에서 재사용할때 사용
1 2 3 4 5 6 7 8 class A: def plus(self): code1 class B(A): def minus(self): code1 # super().plus() code2
1 2 3 4 5 6 7 8 9 10 class Marine : def __init__ (self ): self.health = 40 self.attack_pow = 5 def attack (self, unit ): unit.health -= self.attack_pow if unit.health <= 0 : unit.health = 0
1 2 3 4 5 6 class Marine2 (Marine ): def __init__ (self ): super ().__init__() self.max_health = 40
1 marine.health, marine.attack_pow, marine.max_health
(40, 5, 40)
3. class의 getter, setter
객체의 내부 변수에 접근할때 특정 로직을 거쳐서 접근시키는 방법
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class User : def __init__ (self, first_name, last_name ): self.first_name = first_name self.last_name = last_name def setter (self, first_name ): if len (first_name) >= 3 : self.first_name = first_name else : print("error" ) def getter (self ): print("getter" ) return self.first_name.upper() def disp (self ): print(self.first_name, self.last_name) name = property (getter, setter)
1 user1 = User("andy" , "kim" )
'andy'
getter
'ANDY'
getter
'JOHN'
4. non public
mangling 이라는 방법으로 다이렉트로 객체의 변수에 접근하지 못하게 하는 방법
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Calculator : def __init__ (self, num1, num2 ): self.num1 = num1 self.__num2 = num2 def getter (self ): return self.__num2 def setter (self, num2 ): num2 = 1 if num2 == 0 else num2 self.__num2 = num2 def __disp (self ): print(self.num1, self.__num2) def div (self ): self.__disp() return self.num1/self.__num2 number2 = property (getter, setter)
1 2
0.5
2
1 1
1.0
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-200-9422eadacb85> in <module>
----> 1 calc.__num2
AttributeError: 'Calculator' object has no attribute '__num2'
1
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-203-1997f957eed5> in <module>
----> 1 calc.__disp()
AttributeError: 'Calculator' object has no attribute '__disp'
1 calc._Calculator__disp()
1 1
5. is a & has a
클래스를 설계하는 개념
A is a B
A 는 B이다. 상속을 이용해서 클래스를 만드는 방법
A has a B
A 는 B를 가진다. A는 B객체를 가지고 클래스를 만드는 방법
1 2 3 4 5 class Person : def __init__ (self, name, email ): self.name = name self.email = email
1 2 3 class Person2 (Person ): def info (self ): print(self.name, self.email)
1 p = Person2("andy" , "andy@gmail.com" )
andy andy@gmail.com
1 2 3 4 5 6 7 class Name : def __init__ (self, name ): self.name_str = name class Email : def __init__ (self, email ): self.email_str = email
1 2 3 4 5 6 class Person : def __init__ (self, name_obj, email_obj ): self.nmae = name_obj self.email = email_obj def info (self ): print(name.name_str, email.email_str)
1 2 3 name = Name("andy" ) email = Email("andy@gmail.com" ) p = Person(name, email)
andy andy@gmail.com
Magic(Spacial) Method
compare
‘eq ‘: ==
‘ne ‘: !=
‘lt ‘: <
calculate
repr : 객체의 내용을 출력(개발자용)
str : 객체의 내용을 출력
True
True
3
'12'
1 2 3 4 5 6 7 8 9 10 11 12 class Txt : def __init__ (self, txt ): self.txt = txt def __eq__ (self, txt_obj ): return self.txt.lower() == txt_obj.txt.lower() def __repr__ (self ): return "Txt(txt={})" .format (self.txt) def __str__ (self ): return self.txt
1 2 3 t1 = Txt("python" ) t2 = Txt("PYTHON" ) t3 = t1
1 t1 == t2, t1 == t3, t2 == t3
(True, True, True)
Txt(txt=python)
python
range(0, 5)
1 2 3 4 5 6 7 8 9 10 11 12 13 class Integer : def __init__ (self, number ): self.number = number def __add__ (self, obj ): return self.number + obj.number def __str__ (self ): return str (self.number) def __repr__ (self ): return str (self.number)
1 2 3 num1 = Integer(1 ) num2 = Integer(2 ) num1 + num2
3
1
2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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 (money-self.asset)) def insert (self, money ): self.asset += money print("{}원 입금" .format (money)) def add_interest (self ): self.asset *= self.interest print("이자 지급" ) def __repr__ (self ): return "Account(asset:{}, interest:{})" .format (self.asset, self.interest)
1 account1 = Account(10000 )
Account(asset:10000, interest:1.05)
금액부족 : 2000원
2000원 입금
Account(asset:12000, interest:1.05)
이자 지급
Account(asset:12600.0, interest:1.05)