어제 했던 class 복습
__summary class__
어제 homework 마린과 메딕을 클래스로 공격과 힐을 구현해라!
class Marine:
def __init__(self, health=40, attack_pow=5):
self.health = self.max_health = health
self.attack_pow = attack_pow
def attack(self, target):
target.health -= self.attack_pow
if target.health < 0:
target.health = 0
class Medic:
def __init__(self, health=60, heal_pow=6):
self.health = self.max_health = health
self.heal_pow = heal_pow
def heal(self, target):
target.health += self.heal_pow
if target.health > target.max_health:
target.health = target.max_health
m1 = Marine()
m2 = Marine()
medic = Medic()
m1.health, m2.health
>>>>>>>>
(40, 40)
m1.attack(m2)
m1.health, m2.health
>>>>>
(40, 35)
medic.heal(m2)
m1.health, m2.health
>>>>>>>>>>
(40, 40)
객체의 내부 변수에 접근할 때 특정 메서드를 거쳐서 접근할수 있도록 하는 방법
class Person:
def __init__(self, pw):
self.hidden_pw = pw
@property
def pw(self):
print('getter')
return self.hidden_pw[:2] + '****'
@pw.setter
def pw(self, new_pw):
print('setter')
input_pw = input('insert password : ')
if input_pw == self.hidden_pw:
self.hidden_pw = new_pw
else:
print('wrong password!')
person = Person('abcd')
person.pw = 'qwer'
>>>>>>
setter
insert password : abcd
person.pw
>>>>>>
getter
qw****
class Person:
def __init__(self, pw):
self.hidden_pw = pw
def getter(self):
print('getter')
return self.hidden_pw
def setter(self, new_pw):
print('setter')
input_pw = input('insert password : ')
if input_pw == self.hidden_pw:
self.hidden_pw = new_pw
else:
print('wrong password!')
pw = property(getter, setter)
person = Person('abcd')
person.__hidden_pw = 'qqqq'
# person.pw
# _Person__hidden_pw
# dir(person)
person._Person__hidden_pw = 'aaaa'
person.__hidden_pw = 'qqqq' # X
person.pw = 'wwww' # O
>>>>>>
setter
insert password : www
wrong password!
인스턴스 메서드 : 파라미터 self : 객체를 이용하여 메서드 호출
클래스 메서드 : 파라미터 cls : 클래스를 이용하여 메서드 호출 : 객체로 생성된 초기 변수값을 모두 수정
스태틱 메서드 : 파라미터 X : 객체를 선언하지 않고 메서드 호출
class Account:
interest = 1.01 # 이자율 1%
def __init__(self, asset=10000):
self.asset = asset
def __show_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')
account1 = Account(10000)
account2 = Account(20000)
account3 = Account(30000)
account1.asset, account2.asset, account3.asset,\
account1.interest, account2.interest, account3.interest
>>>>>>
(10000, 20000, 30000, 1.01, 1.01, 1.01)
account1.change_interest(1.09)
account1.asset, account2.asset, account3.asset,\
account1.interest, account2.interest, account3.interest
>>>>>>>
(10000, 20000, 30000, 1.09, 1.01, 1.01)
# 클래스 메서드 사용
# 해당 클래스로 부터 만들어진 객체의 변수를 한꺼번에 변경할때 사용
Account.cls_change_interest(1.04)
account1.asset, account2.asset, account3.asset,\
account1.interest, account2.interest, account3.interest
>>>>>>>>
(10000, 20000, 30000, 1.09, 1.04, 1.04)
Account.interest_grade(account1.interest)
Account.interest_grade(account2.interest)
>>>>>>
high interest
middle interest
# is a
class Info:
def __init__(self, name, email):
self.name = name
self.email = email
class Person(Info):
def show(self):
print(self.name, self.email)
person = Person('peter', 'peter@gmail.com')
person.name, person.email
>>>>>>
('peter', 'peter@gmail.com')
# has a
class Name:
def __init__(self, name):
self.name_str = name
class Email:
def __init__(self, email):
self.email_str = email
class Person:
def __init__(self, name_obj, email_obj):
self.name = name_obj
self.email = email_obj
def show(self):
print(self.name.name_str, self.email.email_str)
name_obj = Name('peter')
email_obj = Email('peter@gmail.com')
person = Person(name_obj, email_obj)
person.show()
>>>>>
peter peter@gmail.com
RAM > SSD(HDD) # RAM < SSD(HDD)
pickle : 질렬화, 입출력 속도 빠름
import pickle
with open('sales.pkl', 'rb') as file:
data = pickle.load(file)
data.keys()
>>>>>
dict_keys(['meeting_count', 'meeting_time', 'sales'])
# 상관계수 구하기
import numpy as np
np.corrcoef(data['meeting_count'], data['sales'])[0, 1],\
np.corrcoef(data['meeting_time'], data['sales'])[0, 1]
>>>>>>>>>
(0.7822244248616061, 0.22829902637616528)
# 모델링 : 미팅횟수, 미팅 시간으로 매출 예측 모델
import pandas as pd
features = pd.DataFrame({
'meeting_count': data['meeting_count'],
'meeting_time': data['meeting_time'],
})
target = data['sales']
features[:2]
※ 오늘 또 명심해야 할것 class의 데이터 타입은 사용자 정의이다!