[제로베이스] 데이터 사이언스 15기 - (05-09 파이썬 중급 스터디노트)

윤태호·2023년 5월 9일
0
post-thumbnail

오늘 수강한 강의 - 파이썬 중급 (14 ~ 29)

14 패키지 ~ 29 클래스 상속

패키지

  • 패키지를 이용하면 관련 있는 모듈을 그룹으로 관리할 수 있다

site-packages

  • site-packages에 있는 모듈은 어디서나 사용할 수 있다

venv - Lib - site-pakages 폴더에 모듈을 옮기면 어디서나 사용 가능

자주 사용하는 모듈

  • 수학, 난수, 시간 모듈은 코딩할때 유용하게 사용된다

  • math 모듈

기본 제공

sum() -> 덧셈 
max() -> 최댓값 
min() -> 최솟값
pow(a, b) -> a의 b제곱
round(a, b)-> a를 소수점 b자리에서 반올림

모듈 제공

import math
print(math.fabs(a)) -> a의 절댓값
print(math.ceil(a)) -> a 올림
print(math.floor(a)) -> a 내림
print(math.trunc(a)) -> 버림(소수점 뒷자리)
print(math.gcd(a, b)) -> a와 b의 최대공약수
print(math.factorial(a)) -> a에 대한 팩토리얼
print(math.sqrt(a)) -> a의 제곱근
  • random 모듈

난수

import random
print(random.random()) -> 0이상 1미만 난수
print(random.randint(a, b)) -> a이상 b이하 난수
print(random.randrange(a, b)) -> a이상 b미만 난수
print(random.sample(range(a, b), c)) -> a이상 b미만 난수 c개

그 외

listVar = [0, 1, 2, 3, 4, 5, 6]
print(random.choice(listVar)) -> 리스트에서 무작위 한 개 추출
random.shuffle(listVar) -> 리스트 섞음
  • time 모듈
import time
lt = time.localtime()
print(lt) -> 전체 출력
print(lt.tm_year) -> 년도만 출력
print(lt.tm_mon) -> 월만 출력
print(lt.tm_mday) -> 일만 출력
print(lt.tm_hour) -> 시간만 출력
print(lt.tm_min) -> 분만 출력
print(lt.tm_sec) -> 초만 출력
print(lt.tm_wday) -> 요일만 출력

객체지향 프로그래밍

  • 객체를 이용한 프로그램으로 객체는 속성과 기능으로 구성된다

객체(Object) = 속성(Attribute) + 기능(Function)
ex) 계산기(Object)
속성 : 숫자
기능 : 덧셈, 뺄셈, ....

  • 객체는 클래스에서 생성된다 (하나의 클래스에 여러개의 객체 생성 가능)

  • 코드 재사용, 모듈화에 좋다

클래스와 객체 생성

  • 클래스는 class 키워드와 속성(변수), 기능(함수)을 이용하여 만든다

  • (실습) 비행기 클래스를 만들고 비행기 객체 5개 생성
class AirPlane:
    def __init__(self, color, length, weight):
        self.color = color
        self.length = length
        self.weight = weight
    def takeOff(self):
        print('take-off')
    def landing(self):
        print('landing')
    def printAirplaneInfo(self):
        print('color: {}' .format(self.color))
        print('length: {}'.format(self.length))
        print('weight: {}'.format(self.weight))
airPlane1 = AirPlane('red', 200, 2000)
airPlane2 = AirPlane('blue', 150, 2200)
airPlane3 = AirPlane('green', 180, 2100)
airPlane4 = AirPlane('white', 220, 1900)
airPlane5 = AirPlane('black', 210, 2300)
airPlane1.printAirplaneInfo()
airPlane2.printAirplaneInfo()
airPlane3.printAirplaneInfo()
airPlane4.printAirplaneInfo()
airPlane5.printAirplaneInfo()

객체 속성 변경

  • 객체 속성은 변경할 수 있다
class NewGenerationPC:
    def __init__(self, name, cpu, memory, ssd):
        self.name = name
        self.cpu = cpu
        self.memory = memory
        self.ssd = ssd
    def doExcel(self):
            print('EXCEL RUN!!')
    def doPhotoshop(self):
            print('PHOTOSHOP RUN!!')
    def printPCInfo(self):
            print('name: {}' .format(self.name))
            print('cpu: {}' .format(self.cpu))
            print('memory: {}' .format(self.memory))
            print('ssd: {}'.format(self.ssd))
myPc = NewGenerationPC('myPC', 'i5', '16G', '256G')
myPc.printPCInfo()
friendPc = NewGenerationPC('friendPC', 'i7', '32G', '512G')
friendPc.printPCInfo()

객체 속성 변경

myPc.cpu = 'i9'
myPc.memory = '64G'
myPc.ssd = '1T'
myPc.printPCInfo()

객체와 메모리

  • 변수는 객체의 메모리 주소를 저장하고 이를 이용하여 객체를 참조한다
class Robot:
    def __init__(self, color, height, weight):
        self.color = color
        self.height = height
        self.weight = weight
    def printRobotInfo(self):
        print('-' * 20)
        print(f'color: {self.color}')
        print(f'height: {self.height}')
        print(f'weight: {self.weight}')
        print('-' * 20)

동일한 메모리 주소를 가리킴

rb1 = Robot('red', 200, 80)
rb2 = Robot('blue', 300, 120)
rb3 = rb1

rb1과 rb3의 값이 같게 나옴

rb1.printRobotInfo()
rb2.printRobotInfo()
rb3.printRobotInfo()

rb1의 값만 바꿔도 rb3도 같이 바뀜

rb1.color = 'gray'
rb1.height = 250
rb1.weight = 100

객체 복사

  • 얕은 복사

    객체 주소를 복사하는 것으로 객체 자체가 복사 되지 않는다

  • 깊은 복사

    객체 자체를 복사하는 것으로 또 하나의 객체가 만들어진다

class TemCls:
    def __init__(self, n, s):
        self.number = n
        self.str = s
    def printClsInfo(self):
        print(f'self.number: {self.number}')
        print(f'self.str: {self.str}')

얕은 복사

tc1 = TemCls(10, 'Hello')
tc2 = tc1
tc1.printClsInfo()
tc2.printClsInfo()
tc2.number = 3.14
tc2.str = 'Bye'
tc1.printClsInfo()
tc2.printClsInfo()

깊은 복사

import copy
tc1 = TemCls(10, 'Hello')
tc2 = copy.copy(tc1)
tc1.printClsInfo()
tc2.printClsInfo()
tc2.number = 3.14
tc2.str = 'Bye'
tc1.printClsInfo()
tc2.printClsInfo()
  • 리스트 깊은 복사
import copy
scores = [9, 8, 5, 7, 6, 10]
scoresCopy = []
scoresCopy = scores
print(f'id(scores): {id(scores)}')
print(f'id(scoresCopy): {id(scoresCopy)}')

for 문

for s in scores:
    scoresCopy.append(s)

extend

scoresCopy.extend(scores)

copy

scoresCopy = scores.copy()

:

scoresCopy = scores[:]

클래스 상속

  • 클래스는 또 다른 클래스를 상속해서 내 것처럼 사용할 수 있다
class NormalCar:
    def drive(self):
        print('[NormalCar] drive() called!!')
    def back(self):
        print('[NormalCar] back() called!!')

class TurboCar () 안에 NormalCar를 넣어 상속

class TurboCar(NormalCar):
    def turbo(self):
        print('[TurboCar] turbo() called!!')

상속 후 NormalCar의 모든 기능 사용 가능

myTurboCar = TurboCar()
myTurboCar.turbo()
myTurboCar.drive()
myTurboCar.back()

생성자 23 ~ 24

생성자

  • 객체가 생성될 떄 생성자를 호출하면 __init__()가 자동 호출된다
class Calculator:
    def __init__(self):
        print('[Calculator] __init__() called!!')

생성자 호출

cal = Calculator()
  • __init__()가 속성을 초기화 한다
class Calculator:
    def __init__(self, n1, n2):
        print('[Calculator] __init__() called!!')
        self.num1 = n1
        self.num2 = n2
cal = Calculator(10, 20)
print('cal.num1: {}. format(cal.num1))
print('cal.num2: {}. format(cal.num2))
  • 상위 클래스의 속성을 초기화하기 위하여 super()를 사용한다
class P_Class:
    def __init__(self, pNum1, pNum2):
        print('[pClass] __init__()')
        self.pNum1 = pNum1
        self.pNum2 = pNum2

super()를 사용해 상위클래스의 속성 초기화

class C_Class(P_Class):
    def __init__(self, cNum1, cNum2):
        print('[cClass] __init__()')
        super().__init__(100, 200)
        self.cNum1 = cNum1
        self.cNum2 = cNum2
cls = C_Class(10, 20)
  • (실습) 중간고사 클래스와 기말고사 클래스를 상속관계로 만들고 각각의 점수를 초기화, 총점 및 평균을 반환하는 기능 만들기
class MidExam:
    def __init__(self, s1, s2, s3):
        print('[MidExam] __init__()')
        self.mid_kor_score = s1
        self.mid_eng_score = s2
        self.mid_mat_score = s3
    def printScores(self):
        print('mid_kor_score: {}' .format(self.mid_kor_score))
        print('mid_eng_score: {}' .format(self.mid_eng_score))
        print('mid_mat_score: {}' .format(self.mid_mat_score))
class EndExam(MidExam):
    def __init__(self, s1, s2, s3, s4, s5, s6):
        print('[EndExam] __init__()')
        super().__init__(s1, s2, s3)
        self.end_kor_score = s4
        self.end_eng_score = s5
        self.end_mat_score = s6
    def printScores(self):
        super().printScores()
        print('end_kor_score: {}' .format(self.end_kor_score))
        print('end_eng_score: {}' .format(self.end_eng_score))
        print('end_mat_score: {}' .format(self.end_mat_score))
    def getTotalScore(self):
        total = self.mid_kor_score + self.mid_eng_score + self.mid_mat_score
        total += self.end_kor_score + self.end_eng_score + self.end_mat_score
        return total
    def getAverageScore(self):
        return self.getTotalScore() / 6
exam = EndExam(85, 90, 88, 75, 85, 95)
exam.printScores()
print('Total: {}' .format(exam.getTotalScore()))
print('Average: {}' .format(round(exam.getAverageScore(), 2)))

25 다중 상속 ~ 29 예외처리

다중 상속

  • 2개 이상의 클래스를 상속한다
class Car01:
    def drive(self):
        print('drive() method called!!')
class Car02:
    def turbo(self):
        print('turbo() method called!!')
class Car03:
    def fly(self):
        print('fly() method called!!')

다중 상속을 이용하여 Car01, Car02, Car03의 기능 모두 사용 가능

class Car(Car01, Car02, Car03):
    def __int__(self):
        pass
myCar = Car()
myCar.drive()
myCar.turbo()
myCar.fly()
  • (실습) Calculator
class BasicCalculator:
    def add(self, n1, n2):
        return n1 + n2
    def sub(self, n1, n2):
        return n1 - n2
    def mul(self, n1, n2):
        return n1 * n2
    def div(self, n1, n2):
        return n1 / n2
class DeveloperCalculator:
    def mod(self, n1, n2):
        return n1 % n2
    def flo(self, n1, n2):
        return n1 // n2
    def exp(self, n1, n2):
        return n1 ** n2
class Calculator(BasicCalculator, DeveloperCalculator):
    def __init__(self):
        pass
cal = Calculator()
print('cal.add(10, 20): {}' .format(cal.add(10, 20)))
print('cal.sub(10, 20): {}' .format(cal.sub(10, 20)))
print('cal.mul(10, 20): {}' .format(cal.mul(10, 20)))
print('cal.div(10, 20): {}' .format(cal.div(10, 20)))
print('cal.mod(10, 20): {}' .format(cal.mod(10, 20)))
print('cal.flo(10, 20): {}' .format(cal.flo(10, 20)))
print('cal.exp(2, 5): {}' .format(cal.exp(2, 5)))

오버라이딩

  • 하위 클래스에서 상위 클래스의 메서드를 재정의(override) 한다
class Robot:
    def __init__(self, c, h ,w):
        self.color = c
        self.height = h
        self.weight = w
    def fire(self):
        print('미사일 발사!!')
    def printRobotInfo(self):
        print('color: {}'. format(self.color))
        print('height: {}'. format(self.height))
        print('weight: {}'. format(self.weight))
class NewRobot(Robot):
    def __init__(self, c, h ,w):
        super().__init__(c, h, w)
    def fire(self):
        print('레이저 발사!!')

미사일 발사가 아닌 레이저 발사가 출력됨(override)

myRobot = NewRobot('blue', 200, 300)
myRobot.printRobotInfo()
myRobot.fire()

추상 클래스

  • 상위 클래스에서 하위 클래스에 메서드 구현을 강요한다
from abc import ABCMeta
from abc import abstractmethod
class AirPlane(metaclass=ABCMeta):
    @abstractmethod
    def flight(self):
        pass
    def forward(self):
        print('전진!!')
    def backward(self):
        print('후진!!')

상위 클래스에서 flight가 구현 되지 않았기 때문에 하위클래스에서 입력해야만 한다

class Airliner(AirPlane):
    def __init__(self, c):
        self.color = c
    def flight(self):
        print('시속 400km/h 비행!!')
al = Airliner('red')
al.flight()
al.forward()
al.backward()

예외

  • 문법적인 문제는 없으나 실행 중 발생하는 예상치 못한 문제

  • 예외 종류

10 / 0 -> ZeroDivisionError

def mul(n1, n2):
    print(n1 * n2)
firstNum = int(input('first number: '))
secondNum = int(input('second number: '))

ValueError

int('Hello')

IndexError

list = [1, 2, 3, 4, 5, 6]
print(tempList[6])

예외 처리

  • 예상하지 못한 예외가 프로그램 전체 실행에 영향이 없도록 처리함

  • 예외 발생 예상 구문을 try ~ except로 감싼다

n1= 10; n2 = 0
try:
    print(n1 / n2)
except:
    print('예상치 못한 예외가 발생했습니다.')
    print('다른 프로그램 실행에는 문제 없습니다.')
  • (실습) 사용자로부터 숫자 5개를 입력받을 때 숫자가 아닌 자료형이 입력되면 예외 처리하는 프로그램
nums = []
n = 1
while n < 6:
    try:
        num = int(input('input number: '))
    except:
        print('예외 발생!')
        continue
    nums.append(num)
    n += 1
print('nums: {}' .format(nums))

총평

재미있었던 부분

에러가 생기는 부분과 그 에러를 해결할때 쓸 수있는 방법들을 배운것이 가장 즐겁게 배운 부분이다

어려웠던 부분

분명 강의를 볼때는 이해가 됬던 것들이 상속부분에서 직접 실습 문제를 풀어볼때는 헷갈렸었다
기초부분에 비하여 많이 어려워져서 실습 문제 풀때는 더 많은 생각을 해야 코드를 짤 수 있었던 것 같다

느낀점 및 내일 학습 계획

전에 부분도 다 익혔는지 확실치 않은데 새로운 개념들을 더 머리에 넣으니 걱정되는 부분도 있지만 계속 직접 코드를 짜보다보면 분명 손에 익고 이해되는 부분도 있으니 계속 해보려 한다
내일은 파이썬 중급 30 ~ 39, 파이썬 중급 문제풀이 5 까지 학습할 예정이다 오늘 배운 내용이 내일도 기억에 남길 바란다 :)

profile
데이터 부트캠프 참여중

0개의 댓글