"객체 지향 프로그래밍"
객체 = 속성 + 기능
객체는 클래스에서 생성
객체 사용 장점 : 모듈화에 좋다 (가장 이상적인 프로그램이 될 수 있음)
객체 속성은 변경할 수 O
변수는 객체의 메모리 주소를 저장하고, 이를 이용하여 객체 참조
얕은 복사 : 객체 주소를 복사하는 것 (객체 자체가 복사 X)
깊은 복사 : 객체 자체를 복사하는 것 (또 하나의 독립적인 객체 생성)
# 선수의 원본 점수를 이용해서 평균을 출력
# 최고값과 최저값을 제외한 평균을 출력해야 함
plaOriSco = [8.7, 9.1, 8.9, 9.0, 7.9, 9.5, 8.8, 8.3]
plaCopSco = plaOriSco.copy()
plaOriSco.sort()
plaCopSco.sort()
plaCopSco.pop(0) # 최저값 제외
plaCopSco.pop() # 최고값 제외
print('plaOriSco : {}'.format(plaOriSco))
print('plaCopSco : {}'.format(plaCopSco))
oriTot = round(sum(plaOriSco), 2)
oriAvg = round(oriTot / len(plaOriSco), 2)
print('Original Total : {}'.format(oriTot))
print('Original Average : {}'.format(oriAvg))
copTot = round(sum(plaCopSco), 2)
copAvg = round(copTot / len(plaCopSco), 2)
print('Copy Total : {}'.format(copTot))
print('Copy Average : {}'.format(copAvg))
print('oriAvg - copAvg = {}'.format(oriAvg - copAvg))
# 중간고사 클래스와 기말고사 클래스를 상속관계로 만들고 각각의 점수를 초기화
# 총점 및 평균 반환 기능도 추가
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(f'mid_kor_score : {self.mid_kor_score}')
print(f'mid_eng_score : {self.mid_eng_score}')
print(f'mid_mat_score : {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(f'end_kor_score : {self.end_kor_score}')
print(f'end_eng_score : {self.end_eng_score}')
print(f'end_mat_score : {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(f'Total : {exam.getTotalScore()}')
print(f'Average : {exam.getAverageScore()}')
# 삼각형 넓이를 계산하는 클래스를 만들고 이를 상속하는 클래스에서 getArea()를 오버라이딩
class TriangleArea :
def __init__(self, w, h) :
self.width = w
self.height = h
def printTriangleAreaInfo(self) :
print(f'width : {self.width}')
print(f'height : {self.height}')
def getArea(self) :
return self.width * self.height / 2
class NewTriangleArea(TriangleArea) :
def __init__(self,w,h) :
super().__init__(w,h)
def getArea(self):
return str(super().getArea())+'㎠'
ta = NewTriangleArea(7,5)
ta.printTriangleAreaInfo()
triangleArea = ta.getArea()
print(f'TriangleArea : {triangleArea}')
from abc import ABCMeta
from abc import abstractmethod
class AirPlane(metaclass=ABCMeta) :
@abstractmethod
def flight(self) :
pass
class Airliner(Airplane) :
def flightl(self) :
print('시속 400km/h 비행 !')
class NotUseZeroException(Exception) :
def __init__(self,n) :
super().__init__(f'{n}은 사용할 수 없습니다 !')
def divCalculator(num1, num2) :
if num2 == 0 :
raise NotUseZeroException(num2)
else :
print(f'{num1} / {num2} = {num1 / num2}')
num1 = int(input('input number1 : '))
num2 = int(input('input number2 : '))
try :
divCalculator(num1,num2)
except NotUseZeroException as e :
print(e)
# 관리자 암호를 입력하고 다음 상태에 따라 예외 처리하는 예외 클래스를 생성해보자
# 암호 길이가 5 미만 : PasswordLengthShortException
# 암호 길이가 10을 초과하는 경우 : PasswordLengthLongException
# 암호가 잘못된 경우 : PasswordWrongException
class PasswordLengthShortException(Exception) :
def __init__(self, str) :
super().__init__(f'{str} : 길이 5 미만 !')
class PasswordLengthLongException(Exception) :
def __init__(self, str) :
super().__init__(f'{str} : 길이 10 초과 !')
class PasswordWrongException(Exception) :
def __init__(self, str) :
super().__init__(f'{str} : 잘못된 비밀번호 !')
adminPw = input('input admin password : ')
try :
if len(adminPw) < 5 :
raise PasswordLengthShortException(adminPw)
elif len(adminPw) > 10 :
raise PasswordLengthLongException(adminPw)
elif adminPw != 'admin12345' :
raise PasswordWrongException(adminPw)
elif adminPw == 'admin12345' :
print('빙고 !')
except PasswordLengthShortException as e1 :
print(e1)
except PasswordLengthLongException as e2 :
print(e2)
except PasswordWrongException as e3 :
print(e3)
try ~ except : 예외 발생 예상 구문을 감싸면 됨
else : 예외가 발생하지 않은 경우 실행하는 구문
finally : 예외 발생과 상관없이 항상 실행
# try ~ except ~ else ~ finally
# 사용자로부터 숫자 5개를 입력받아 짝수, 홀수, 실수로 구분하고 입력한 모든 데이터를 각각 출력하는 프로그램
eveList = [] ; oddList = [] ; floatList = [] ; dataList = []
n = 1
while n < 6 :
try :
data = input('input number : ')
floatNum = float(data)
except :
print('exception raise !')
print('input number again !')
continue
else :
if floatNum - int(floatNum) != 0 :
print('float number !')
floatList.append(floatNum)
else :
if floatNum % 2 == 0 :
print('even number!')
eveList.append(int(floatNum))
else :
print('odd number !')
oddList.append(int(floatNum))
n += 1
finally :
dataList.append(data)
print(f'eveList : {eveList}')
print(f'oddList : {oddList}')
print(f'floatList : {floatList}')
print(f'dataList : {dataList}')
exception : 예외 담당 클래스
raise : 예외 발생 문구 설정 가능
# exception ~ raise
num1 = int(input('input number1 : '))
num2 = int(input('input number2 : '))
try :
print(f'num1 / num2 = {num1/num2}')
except :
print('0으로 나눌 수 없습니다.')
print(f'num1 * num2 = {num1 * num2}')
print(f'num1 - num2 = {num1 - num2}')
print(f'num1 + num2 = {num1 + num2}')
num1 = int(input('input number1 : '))
num2 = int(input('input number2 : '))
try :
print(f'num1 / num2 = {num1/num2}')
except Exception as e:
print(f'exception : {e}')
print(f'num1 * num2 = {num1 * num2}')
print(f'num1 - num2 = {num1 - num2}')
print(f'num1 + num2 = {num1 + num2}')
def divCalculator(n1,n2) :
if n2 != 0 :
print(f'num1 / num2 = {num1/num2}')
else :
raise Exception('0으로 나눌 수 없습니다.')
num1 = int(input('input number1 : '))
num2 = int(input('input number2 : '))
try :
divCalculator(num1,num2)
except Exception as e :
print(f'Exception : {e}')
# 사용자가 문자 메시지를 보낼때 10글자 이하면 SMS로 발송하고,
# 10글자를 초과하면 MMS로 발송하는 프로그램을 예외처리를 이용해서 만들어보자
def sendSMS(msg) :
if len(msg) > 10 :
raise Exception('길이 초과 ! MMS 전환 후 발송 !', 1)
else :
print('SMS 발송 !')
def sendMMS(msg) :
if len(msg) <= 10 :
raise Exception('길이 미달 ! SMS 전환 후 발송 !', 2)
else :
print('MMS 발송 !')
msg = input('input message : ')
try :
sendSMS(msg)
except Exception as e :
print(f'e : {e.args[0]}')
print(f'e : {e.args[1]}')
if e.args[1] == 1 :
sendMMS(msg)
elif e.args[1] == 2 :
sendSMS(msg)