techit aischool python summary

김상민·2023년 1월 6일
0

aischool

목록 보기
7/9

어제 했던 class 복습
__summary class__

  • 변수, 함수를 묶어서 코드를 작성하는 방법
  • 객체지향을 구현하는 문법
    • 객체지향 : 실제세계를 모델링하여 프로그램을 개발하는 개발방법론 : 협업이 용이함
  • 클래스 사용법
    • 클래스선언(코드작성) > 객체생성(메모리사용) > 메서드실행(코드실행)
    • 클래스선언(설계도작성) > 객체생성(제품생산) > 메서드실행(기능사용)
  • 클래스 식별자 : PascalCase
  • class, self(객체자신)
  • 클래스는 사용자 정의 데이터 타입이다.
    • type(account) : Account > 클래스는 데이터타입이다.
    • Account 클래스는 직접 만듦 > 클래스는 사용자 정의 데이터 타입이다.
    • 객체는 어떤 데이터타입(클래스)으로 만들어졌는지에 따라서 사용가능한 변수, 함수가 다르다.
  • 스페셜 메서드
    • 특별한 기능을 하는 메서드
    • init() : 생성자 메서드
      • 객체가 생성될때 실행되는 메서드
      • 메서드에서 사용되는 변수를 초기화 할때 사용 > 불량품 객체가 생성되는 것을 줄일수 있음
    • add() : + 연산자 정의하는 메서드
      • int 데이터타입의 + 연산과 str 데이터타입의 + 연산이 다르게 수행
      • python의 list와 numpy의 ndarray 데이터타입이 수행되는 연산이 다르다. > ndarray 연산이 속도가 빠르다
    • str(), repr() : print() 함수, ipython에서 출력하는 기능을 수행
  • 상속
    • 다른 클래스의 변수, 함수를 가져오는 방법
    • 다중상속 가능

어제 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)

getter, setter

객체의 내부 변수에 접근할 때 특정 메서드를 거쳐서 접근할수 있도록 하는 방법

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****

non public

  • mangliing : 변수에 직접적으로 접근하는것을 막는 방법
  • 사용법 : 변수형 앞에 __을 붙임
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, has a 개념
  • is a : A is a B : 상속을 이용해서 클래스 설계
  • has a : A has a B : 객체를 객체에 넣어서 클래스 설계
  • 두가지 방법을 혼용해서 사용
  • is a
# 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
# 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의 데이터 타입은 사용자 정의이다!

profile
꾸준히 하고싶다

0개의 댓글