본문 바로가기
제로베이스 데이터 스쿨/일일 스터디 노트

6일차 스터디노트/ 파이썬 객체 지향 프로그래밍, 클래스, 예외 / 제로베이스 데이터 취업스쿨

by 김뎀뎀 2023. 1. 9.

📗 6일차 공부 내용 요약

[파이썬]

1. 모듈 : 자주 사용하는 외부 모듈을 알아보았다.

2. 객체지향 프로그래밍 : 객체의 개념, 클래스와 객체 생성, 복사, 클래스 상속, 생성자, 오버라이딩, 추상클래스에 대해 알아보았다.

3. 예외 : 예외의 개념, 예외 처리에 대해 알아보았다.

 


📖  6일차 공부 내용 자세히

1. 자주 사용하는 외부 모듈

■ 수학 관련 함수

#합 sum()
listVar = [ 2, 5, 3.14, 30]
print(f'sum(listVar) : {sum(listVar)}') #sum(listVar) : 40.14

#최댓값 max()
listVar = [ 2, 5, 3.14, 30]
print(f'max(listVar) : {max(listVar)}') #max(listVar) : 30

#거듭제곱 pow(n1,n2)
print(f'pow(13,2) : {pow(13,2)}') #pow(13,2) : 1728

#반올림 round(n1, n2)
print(f'round(3.141592, 2) : {round(3.141592, 2)}') #round(3.141592, 2) : 3.14

■ math 모듈

import math

#절댓값 fabs(n)
print(f'math.fabs(-10) : {math.fabs(10)}') #math.fabs(-10) : 10.0
print(f'math.fabs(-0.12345) : {math.fabs(-0.12345)}') #math.fabs(-0.12345) : 0.12345

#올림 ceil(n)
print(f'math.ceil(5.21): {math.ceil(5.21)}') #math.ceil(5.21): 6
print(f'math.ceil(-5.21): {math.ceil(-5.21)}') #math.ceil(-5.21): -5

#내림 floor(n)
print(f'math.floor(5.21) : {math.floor(5.21)}') #math.floor(5.21) : 5
print(f'math.floor(-5.21) : {math.floor(-5.21)}') #math.floor(-5.21) : -6

#버림 trunc(n)
print(f'math.trunc(5.21) : {math.trunc(5.21)}') #math.trunc(5.21) : 5
print(f'math.trunc(-5.21) : {math.trunc(-5.21)}') #math.trunc(-5.21) : -

#최대공약수 gcd(n1,n2)
print(f'math.gcd(14,21) : {math.gcd(14,21)}') #math.gcd(14,21) : 7

#팩토리얼 factorial(n)
print(f'math.factorial(10) : {math.factorial(10)}') #math.factorial(10) : 3628800

#제곱근 sqrt(n)
print(f'math.sqrt(4): {math.sqrt(4)}') #math.sqrt(4): 2.0

■ time 모듈

import time

lt = time.localtime()
print(f'time.localtime(): {lt}')
#time.localtime(): time.struct_time(tm_year=2023, tm_mon=1, tm_mday=9, tm_hour=10, tm_min=13, tm_sec=27, tm_wday=0, tm_yday=9, tm_isdst=0)

print(f'lt.tm_year : {lt.tm_year}') #연도
print(f'lt.tm_mon : {lt.tm_mon}') #월
print(f'lt.tm_mday : {lt.tm_mday}') #일
print(f'lt.tm_hour : {lt.tm_hour}') #시간
print(f'lt.tm_min : {lt.tm_min}') #분
print(f'lt.tm_sec : {lt.tm_sec}') #초
print(f'lt.tm_wday : {lt.tm_wday}') #요일

'''
lt.tm_year : 2023
lt.tm_mon : 1
lt.tm_mday : 9
lt.tm_hour : 10
lt.tm_min : 15
lt.tm_sec : 21

 

2. 객체 지향 프로그래밍

■ 객체

  • 객체(object) = 속성(attribuet) + 기능(function)
  • 객체는 클래스에서 생성된다
  • 코드 재사용, 모듈화에 좋다

■ 클래스와 객체

  • 클래스는 class  키워드와 속성(변수) 그리고 기능(함수)를 이용해서 만든다
  • 객체는 클래스의 생성자를 호출한다.
  • 객체 속성은 변경할 수 있다
#클래스 선언
class Car:

    #생성자, 속성
    def __init__(self, col, len):
        self.color = col
        self.length = len

    #기능
    def doStop(self):
        print('STOP!')

    #기능
    def doStrat(self):
        print('START!')

    #기능
    def printCarInfo(self):
        print(f'self.color = {self.color}')
        print(f'self.length = {self.length}')


#객체 2개 생성
car1 = Car('red', 200)
car2 = Car('blue',300)

car1.printCarInfo()
car2.printCarInfo()

 

■ 객체와 메모리

  • 변수는 객체의 메모리 주소를 저장하고 이를 이용해서 객체를 참조한다
  • 객체의 복사본을 만들고 싶다면 copy()를 활용한다 ->  변수명.copy()
#국어,영어,수학 점수를 입력받아 리스트에 저장하고 원본을 유지한 상태로,
#복사본을 만들어 과목별 점수를 10% 올렸을 경우에 평균을 출력해보자.

scores = [int(input('국어 점수 입력 : ')),
          int(input('영어 점수 입력 : ')),
          int(input('수학 점수 입력 : '))]


copyScores = scores.copy() #scores 의 복사본을 만듦

for idx, score in enumerate(copyScores): #enumerate : 인덱스와 원소로 이루어진 터플을 만든다
    result = score * 1.1
    copyScores[idx] = 100 if result > 100 else result
    #과목 점수에 10% 올렸는데 100점 이상일 경우, 100으로 아니면 result로 저장

print(f'이전 평균 : {round( sum(scores) / len(scores) , 2 )}')
print(f'이후 평균 : {round( sum(copyScores) / len(copyScores) , 2 )}')\

'''
국어 점수 입력 : 98
영어 점수 입력 : 99
수학 점수 입력 : 89
이전 평균 : 95.33
이후 평균 : 99.3
'''

💡 위 예제를 작성하면서, enumerate()함수와 튜플 자료형을 알아보고, 기록해보았다

 

[파이썬] for문 / enumerate()함수

📌 enumerate( ) 함수 순서가 있는 데이터를 입력 받아 인덱스 값을 포함한 enuerate 객체를 반환한다 인덱스와 원소로 이루어진 튜플(tuple)을 만들어 준다 for문과 함께 주로 사용하여 자료형의 현재

kim-dem-dem.tistory.com

 

 

[파이썬] 튜플(tuple) 자료형

📌 튜플(tuple) 자료형 튜플은 리스트와 거의 비슷하지만, 다른점은 다음과 같다 리스트는 [ ] 로, 튜플은 ()로 둘러싼다 리스트는 요소 값의 생성, 삭제, 수정이 가능하나 튜플은 요소값의 변경이

kim-dem-dem.tistory.com

■ 얕은 복사와 깊은 복사

  • 얕은 복사란, 객체 주소를 복사하는 것으로 객체 자체가 복사되지는 않는다
  • 깊은 복사란, 객체 자체를 복사하는 것으로 또 다른 하나의 객체가 만들어진다
import copy

scores = [9, 8, 5, 7, 6, 10]
scoresCopy = []


#얕은 복사
scoresCopy = scores
print(f'id(scores) : {id(scores)}') #id()함수 객체의 고유 주소값을 리턴한다
print(f'id(scoresCopy) : {id(scoresCopy)}')

'''
id(scores) : 2619212214528
id(scoresCopy) : 2619212214528
'''

#깊은 복사 (for문 활용)
for s in scores:
    scoresCopy.append(s)

print(f'id(scores) : {id(scores)}') 
print(f'id(scoresCopy) : {id(scoresCopy)}')

'''
id(scores) : 2699560988928
id(scoresCopy) : 2699560839680
'''

#깊은 복사 (copy모듈 활용)
scoresCopy = scores.copy()
print(f'id(scores) : {id(scores)}')
print(f'id(scoresCopy) : {id(scoresCopy)}')

'''
id(scores) : 1512358850816
id(scoresCopy) : 1512358701952
'''

#깊은 복사 (슬라이싱 활용)
scoresCopy = scores[:]
print(f'id(scores) : {id(scores)}')
print(f'id(scoresCopy) : {id(scoresCopy)}')

'''
id(scores) : 1706338332928
id(scoresCopy) : 1706338183680
'''
#선수의 원본 점수를 이용해서 평균을 출력하고,
#원본 점수를 복사한 후 최고값과 최저값을 제외한 평균을 출력하는 프로그램을 만들어보자


plaOriScore = [ 8.7, 9.1, 8.9, 9.0, 7.9, 9.5, 8.8, 8.3]
plaCopScore = plaOriScore.copy()

plaOriScore.sort() #원본 점수 순서대로 정령

plaCopScore.sort() #카피 점수 순서대로 정렬
plaCopScore.pop(0) #카피 점수 최소값 제외
plaCopScore.pop() #카피 점수 최대값 제외

print(f'원본 점수 : {plaOriScore}')
print(f'최저, 최고값 제외 점수 : {plaCopScore}')

oriTot = round(sum(plaOriScore),2) #원본 총점
oriAvg = round(oriTot/len(plaOriScore),2) #원본 평균
print(f'원본 총점 : {oriTot}')
print(f'원본 평균 : {oriAvg}')

copTot = round(sum(plaCopScore),2) #카피 총점
copAvg = round(copTot/len(plaCopScore),2) #카피 평균
print(f'최저,최고값 제외 총점 : {copTot}')
print(f'최저,최고값 제외 평균 : {copAvg}')

'''
원본 점수 : [7.9, 8.3, 8.7, 8.8, 8.9, 9.0, 9.1, 9.5]
최저, 최고값 제외 점수 : [8.3, 8.7, 8.8, 8.9, 9.0, 9.1]
원본 총점 : 70.2
원본 평균 : 8.78
최저,최고값 제외 총점 : 52.8
최저,최고값 제외 평균 : 11.7
'''

💡 위 예제를 작성하면서, list 자료형의 슬라이싱, 정렬, 요소 끄집어내기를 알아보고, 기록해보았다

 

[파이썬] list 자료형 / 리스트 정렬(sort), 리스트 요소 끄집어내기(pop), 리스트 슬라이싱

📌 List 슬라이싱 리스트명 [ 시작번호 : 끝번호 ] 끝번호에 해당하는 것은 포함하지 않는다 시작번호

kim-dem-dem.tistory.com

■ 클래스 상속

  • 클래스는 또 다른 클래스를 상속해서 내 것처럼 사용할 수 있다
  • 다중 상속은 2개 이상의 클래스를 상속하는 것이다
class NomalCar:

    def drive(self):
        print('[NomalCar] drive() called!!')

    def back(self):
        print('[NomalCar] back() called!!')

class TurboCar(NomalCar):

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

myTurboCar = TurboCar()

myTurboCar.turbo()
myTurboCar.drive()
myTurboCar.back()

'''
[TurboCar] turbo() called!!
[NomalCar] drive() called!!
[NomalCar] back() called!!

■ 생성자

  • 객체가 생성될 때 생성자를 호출하면 __int__()가 자동으로 호출된다
  • __int__()가 속성을 초기화한다
  • 상위클래스의 속성을 초기화하기 위해서 super()를 이용한다
#중간고사 클래스와 기말고사 클래스를 상속관계로 만들고 각각의 점수를 초기화하자.
#또한 총점 및 평균을 반환하는 기능도 만들어보자

class MidTerm:

    def __init__(self, s1, s2, s3):
        print('[MidTerm] __init__()')
        self.mid_korScore = s1
        self.mid_ingScore = s2
        self.mid_matScore = s3

    def printScores(self):
        print(f'중간 고사 국어 점수 : {self.mid_korScore}')
        print(f'중간 고사 영어 점수 : {self.mid_ingScore}')
        print(f'중간 고사 수학 점수 : {self.mid_matScore}')

    def mid_total(self):
        return self.mid_matScore

    def avg(self):
        return round(MidTerm.total(self)/3,2)


class FinalTerm(MidTerm):

    def __init__(self, s1, s2, s3, s4, s5, s6):
        print('[FinalTerm] __init__()')
        super().__init__(s1,s2,s3) # MidTerm의 속성으로 올려서 초기화 시킨다.

        self.final_korScore = s4
        self.final_ingScore = s5
        self.final_matScore = s6

    def printScores(self):
        super().printScores()
        print(f'기말 고사 국어 점수 : {self.final_korScore}')
        print(f'기말 고사 영어 점수 : {self.final_ingScore}')
        print(f'기말 고사 수학 점수 : {self.final_matScore}')

    def getTotalScore(self):
        total = self.mid_korScore + self.mid_ingScore + self.mid_matScore
        total += self.final_korScore + self.final_ingScore + self.final_matScore

        return total

    def getAvgScore(self):
        return self.getTotalScore()/6

myScore = FinalTerm(97,98,100,89,99,89)

myScore.printScores()
print(f'총점 : {myScore.getTotalScore()}')
print(f'평균 : {round(myScore.getAvgScore(),2)}')

 

■ 오버라이딩

  • 하위클래스에서 상위클래스의 메서드를 재정의(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(f'self.color : {self.color}')
        print(f'self.height : {self.height}')
        print(f'self.weight : {self.weight}')

class NewRobot(Robot):

    def __init__(self, c, h, w):
        super().__init__( c, h, w) #self 안쓴다

    def fire(self):
        print('레이저 발사!!')

myRobot = NewRobot('red', 200, 400)
myRobot.printRobotInfo()
myRobot.fire()

'''
self.color : red
self.height : 200
self.weight : 400
레이저 발사!!

 

■ 추상클래스

  • 상위클래스에서 하위 클래스에 메서드 구현을 강요한다
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('후진!!')

class Airliner(AirPlane):

    def __init__(self,c):
        self.color = c

    def flight(self):
        print('시속 400km/h 비행!')

class fighterPlane(AirPlane):

    def __init__(self,c):
        self.color = c

    def flight(self):
        print('시속 700km/h 비행!')

al = Airliner('red')
al.flight()
al.forward()
al.backward()

print('-'*30)
fl = fighterPlane('blue')
fl.flight()
fl.forward()
fl.backward()

'''
시속 400km/h 비행!
전진!!
후진!!
------------------------------
시속 700km/h 비행!
전진!!
후진!!
'''

3. 예외

■ 예외

  • 예외는 문법적인 문제는 없으나 실행 중 발생하는 예상치 못한 문제이다
  • 예외 관련 클래스는 Exception 클래스를 상속한다

 

■ 예외처리

  • 예외는 문법적인 문제는 없으나 실행 중 발생하는 예상치 못한 문제이다
try ~ except
예외 발생 예상 구문을 try ~ except로 감싼다
#사용자로부터 숫자 5개를 입력받을 때 숫자가 아닌 자료형이 입력되면 예외 처리하는 프로그램을 만들어보자

nums = []

n=1
while n < 6 :
    try:
        inputNumber = int(input('input number : '))
    except:
        print('예외 발생!')
        continue
    nums.append(inputNumber)
    n += 1

print(f'nums : {nums}')

'''
input number : 1
input number : 2
input number : r
예외 발생!
input number : k
예외 발생!
input number : 3
input number : 4
input number : 5
nums : [1, 2, 3, 4, 5]
'''
try ~ except ~else
예외가 발생하지 않은 경우 else를 실행한다
nums = []

n = 1

while n < 6:

    try:
        num = int(input('input number : '))
    except:
        print('예외발생!')
        continue

    if num % 2 == 0:
        nums.append(num)
        n += 1
    else:
        print('홀수입니다. 다시 입력하세요')
				continue ##굳이 왜 필요할까?

print(f'nums : {nums}')

'''
input number : 2
input number : 1
홀수입니다. 다시 입력하세요
input number : 가가
예외발생!
input number : 4
input number : 6
input number : 8
input number : 2
nums : [2, 4, 6, 8, 2]
'''
finally
예외 발생과 상관없이 항상 실행한다
#사용자로부터 숫자 5개를 입력받아 짝수, 홀수, 실수와 입력한 모든 데이터를 각각 출력하는 프로그램을 만들어보자

evenList = []; oddList = []; floatList = [] ; dataList = []

n = 1

while n < 6 :

    try:
        inputData = input('input number : ')
        num = float(inputData)

    except:
        print('exception raise!')
        continue

    else :
        if num - int(num) == 0:
            if num % 2 == 0:
                print('even number!')
                evenList.append(int(num))
            else:
                print('odd number!')
                oddList.append(int(num))
        else:
            print('float number!')
            floatList.append(num)
    finally:
        dataList.append(inputData)

    n += 1

print(f'evenList : {evenList}')
print(f'oddList : {oddList}')
print(f'floatList : {floatList}')
print(f'dataList : {dataList}')

'''
input number : 3
odd number!
input number : 4
even number!
input number : 3.14
float number!
input number : 가
exception raise!
input number : 6
even number!
input number : 9
odd number!
evenList : [4, 6]
oddList : [3, 9]
floatList : [3.14]
dataList : ['3', '4', '3.14', '가', '6', '9']

➰ 6일차 후기

강의듣고 얼마지나지 않아서는 잘 기억하고 이해하는데, 뒷부분 까지 다 듣고나니 언제 그랬냐는 듯 앞 부분 내용이 흐릿해진다.

이거 정말 내용이 점점 더 쌓이다 보면 더 만만치 않을 것 같다는 생각이 든다.

계속 봐야 익숙해진다는 마음으로~ 자주 돌아봐야겠다! 아자자

 


※본 내용은 제로베이스 데이터 취업 스쿨에서 제공하는 학습 내용에 기반합니다.