- 다중 상속을 남발 할 경우, 프로그램이 다중 상속의 늪에 빠질 수 있음! 주의!
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 flr(self, n1, n2):
return n1 // n2
def exp(self, n1, n2):
return n1 ** n2
class SuperCalculator(BasicCalculator, DeveloperCalculator):
def __init__(self):
pass
mycal = SuperCalculator()
print(mycal.add(10,20))
print(mycal.mod(10, 3)) #1
print(mycal.flr(10, 3)) #3
print(mycal.exp(2, 8)) #256
+하위 클래스에서 상위 클래스의 메서드를 재정의(override) 함
class TriangleArea:
def __init__(self, w, h):
self.width = w
self.height = h
def printTriangleInfo(self):
print(f'가로 길이: {self.width}')
print(f'세로 길이: {self.height}')
def getArea(self):
return self.width * self.height / 2
class myTriArea(TriangleArea): #상위에서 상속 받아와서 예쁘게 꾸며주는 클래스
def __init__(self, w, h):
super().__init__(w, h)
def getArea(self):
return str(super().getArea()) + '㎠' #숫자는 문자로 바꿔주고, 특수문자는 외부에서 찾아서 복붙
mytriangle = myTriArea(7, 5)
mytriangle.printTriangleInfo()
print(f'삼각형 넓이: {mytriangle.getArea()}')
- 상위 클래스에서 하위 클래스에 메서드 구현을 강요
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 Airline(Airplane):
def __init__(self, c):
self.color = c
myAir = Airline('red')
TypeError: Can't instantiate abstract class Airline with abstract method flight
해석: 강요한걸 안했으므로 너에게 줄 것은 없다 (아님)
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('비행')
myAir = Airliner('red')
from abc import ABCMeta
from abc import abstractmethod
class Calculator(metaclass=ABCMeta):
@abstractmethod
def add(self, n1, n2):
pass
@abstractmethod
def sub(self, n1, n2):
pass
@abstractmethod
def mul(self, n1, n2):
pass
@abstractmethod
def div(self, n1, n2):
pass
class DeveloperCalculator(Calculator):
def add(self, n1, n2):
print(n1 + n2)
def sub(self, n1, n2):
print(n1 - n2)
def mul(self, n1, n2):
print(n1 * n2)
def div(self, n1, n2):
print(n1 / n2)
def mod(self, n1, n2):
print(n1 % n2)
def flo(self, n1, n2):
print(n1 // n2)
myCal = DeveloperCalculator()
myCal.add(10, 20)
myCal.mod(10,20)
- 문법적인 문제는 없으나 실행 중 발생하는 예상하지 못한 문제이다.
- 에러는 문법적인 문제가 있거나, 천재지변이 있거나... 예외와는 다름!
print(10/0)
#ZeroDivisionError: division by zero
print(int('hello'))
#ValueError: invalid literal for int() with base 10: 'hello'
list = [1, 2, 3, 4, 5]
print(list[6])
#IndexError: list index out of range
- 예상하지 못한 예외가 프로그램 전체 실행에 영향이 없도록 처리함
🔑 try ~ except
n1 = 10
n2 = 0
try:
print(n1/n2)
except:
print('예상치 못한 문제 발생')
print('다음 프로그램 정상 실행')
print(n1*n2)
print(n1-n2)
print(n1+n2)
nums = []
n = 1
while n < 6:
try:
num = int(input('숫자 입력: '))
nums.append(num)
n += 1
except:
print('숫자를 입력하시오!')
continue
print(nums)
nums = []
n = 1
while n < 6:
try:
num = int(input('숫자 입력: '))
except:
print('예외 발생')
continue
else:
if num % 2 == 0:
nums.append(num)
n += 1
else:
print('짝수를 입력하세요')
continue
print(nums)
evenList = []; oddList = []; floatList = []
n = 1
while n < 6:
try:
userInput = float(input('숫자 입력: '))
except:
print('예외 발생')
continue
else:
if userInput - int(userInput) != 0:
floatList.append(userInput)
elif userInput % 2 == 0:
evenList.append(int(userInput))
else:
oddList.append(int(userInput))
n += 1
continue
print(f'floatList: {floatList}')
print(f'evenList" {evenList}')
print(f'oddList: {oddList}')
- 예외의 발생 유무에 상관없이 무조건 실행!
evenList = []; oddList = []; floatList = []; dataList = []
n = 1
while n < 6:
try:
userInput = input('숫자 입력: ')
floatNum = float(userInput)
except:
print('예외 발생. 숫자를 입력하세요.')
continue
else:
if floatNum - int(floatNum) != 0:
print('float number')
floatList.append(floatNum)
elif floatNum % 2 == 0:
print('even number')
evenList.append(int(floatNum))
else:
print('odd number')
oddList.append(int(floatNum))
finally:
dataList.append(userInput)
n += 1
continue
print(f'evenList: {evenList}')
print(f'oddList: {oddList}')
print(f'floatList: {floatList}')
print(f'dataList: {dataList}')
except Exception as e:
print(f'exception: {e}) #exception: division by zero
def divCalculator(n1, n2):
if n2 != 0:
print(f'{n1} / {n2} = {n1 / n2}')
else:
raise Exception('0으로 나눌 수 없습니다.') #raise 로 예외를 발생시킴
num1 = int(input('숫자 입력: '))
num2 = int(input('숫자 입력: '))
try:
divCalculator(num1, num2)
except Exception as e:
print(f'exception: {e}') #내가 정의한 문구 표시
- args를 알아야 하는데, 초면이므로 검색...했지만 이해하는 것에 실패하였다
- 코드 받아쓰기만 해보고 넘어가자
msg = input('메세지 입력: ')
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 발송')
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)