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의 제곱근
난수
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) -> 리스트 섞음
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 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()
class Calculator: def __init__(self): print('[Calculator] __init__() called!!')
생성자 호출
cal = Calculator()
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))
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)))
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()
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)))
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('다른 프로그램 실행에는 문제 없습니다.')
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 까지 학습할 예정이다 오늘 배운 내용이 내일도 기억에 남길 바란다 :)