[python] 함수, 모듈, 패키지, 객체지향 프로그래밍, 예외 처리, 텍스트 파일

svenskpotatis·2023년 8월 7일
0

01 함수란 ~ 20 객체와 메모리

📌 함수

  • 함수 선언
def addCal():
	n1 = int(input('n1 입력: '))  #실행문
    n2 = int(input('n2 입력: '))
    print(f'n1 + n2 = {n1+n2}')
  • 함수 호출
addCal()
  • 매개변수(parameter), 인수(argurment)
#함수 선언
def functionName(parameter):      
	실행문

#함수 호출
functionName(arguement)          
def greet(customer):
    print(f'{customer}님 안녕하세요.')
    print('{}님 안녕하세요.'.format(customer))
   
greet('홍길동')

>>> 홍길동님 안녕하세요. 
	홍길동님 안녕하세요. 
  • 매개변수 개수가 정해지지 않은 경우 * 사용.
def printNumber(*numbers):
	for number in numbers:
    	print(number, end='')
    print()

지역변수, 전역변수

  • 전역 변수: 함수 밖에 선언된 변수로 어디에서나 사용 가능, 함수 안에서 수정할 수는 x
  • 지역 변수: 함수 안에 선언된 변수로 함수 안에서만 사용 가능
#global: 함수 안에서 전역변수 값 수정하는 키워드
num_out = 10
def printNumbers():
	global num_out
    num_out = 20
    print(f'num_out: {num_out}')

lambda 함수

lambda 키워드를 이용해서 함수 선언을 보다 간단하게 할 수 있다.

def calculator(n1, n2):
	return n1 + n2

returnValue = calculator(10, 20)
print(f'returnValue: {returnValue}')

=>

#functionName = lamda parameter: 실행문

calculator = lambda n1, n2: n1+n2
returnValue = calculator(10, 20)
print(f'returnValue: {returnValue}')

📌 모듈

모듈: 특정 기능을 가지고 있는 파이썬 파일

  • 모듈 만들기

    #모듈 파일(lottoMachine.py)
    import random
    
    def getLottoNumbers():
    	result = random.sample(range(1, 46), 6)
       
        return result
    #실행 파일
    import lottoMachine
    
    lottoNumbers = lottoMachine.getLottoNumbers()
    print(f'lottoNumbers: {lottoNumbers}')
  • import, as, from~as

import calculator
import calculator as cal
from calculator import add
from calculator import *   #모든 기능
  • __name__ 전역변수
#자기 자신이 실행하면
print(f'__name__: {__name__}')
>>>__name__: __main__

#import 해서 실행되면
print(f'__name__: {__name__}')
>>>__name__: addModule
  • 수학 관련 함수
listVar = [1, 5, 6, 12, 2]

#합
sum(listVar)

#최댓값
max(listVar)

#최솟값
min(listVar)

#거듭제곱
pow(13, 2)

#반올림
round(3.141592, 1)    #소수점 첫 번째 자리까지 표현, 두 번째 자리에서 반올림

자주 사용하는 모듈

  • math 모듈
import math

math.fabs(-10)    #절댓값
>>>10

math.ceil(5.21)   #올림
>>>6

math.floor(5.21)   #내림
>>>5

math.trunc(5.21)    #버림
>>>5

math.gcd(14,21)    #최대공약수
>>>7

math.factorial(10)    #팩토리얼
>>>3628800

math.sqrt(4)    #제곱근
>>>2.0
  • random 모듈
  • time 모듈
import time

lt = time.localtime()   #현재 시간
lt.tm_year
lt.tm_mon
lt.tm_mday
lt.tm_hour
lt.tm_min
lt.tm_sec
lt.tm_wday  #요일

📌 패키지

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

  • site-packages

📌 객체지향 프로그래밍

객체

객체(object) = 속성(attribute) + 기능(function)
클래스(Class) -> 객체 생성 -> 객체(Object)
//클래스 이름: 첫 글자 대문자

#클래스 만들기
class Car:      #클래스 선언
	def __init__(self, color, length):
    	self.color = color       #생성자, 속성
        self.length = length
        
    def doStop(self):       #기능1
    	print('STOP!!')
        
    def doStart(self):      #기능2
    	print('START!')

#객체 생성
car1 = Car('red', 200)
car2 = Car('blue', 300)
#실습
class Airplane:
    def __init__(self, nation, personnel):
        self.nation = nation
        self.personnel = personnel

    def doTakeoff(self):
        print('TAKEOFF')

    def doLand(self):
        print('LAND')


airplane1 = Airplane('Korea', 330)
airplane2 = Airplane('Finland', 550)

airplane1.doLand()
print(airplane2.nation)

객체 속성 변경

변수(car1)은 객체의 메모리 주소를 저장.

  • list1.copy(): 리스트 복제
  • enumerate

21 얕은 복사와 깊은 복사 ~ 39 readlines(), readline()

클래스 상속

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

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

class TurboCar(NormalCar):   #TurboCar가 NormalCar를 상속
    def turbo(self):
        print('[TurboCar] turbo() called!!')

myTurboCar = TurboCar()

myTurboCar.turbo()
myTurboCar.drive()

생성자

  • 상위 클래스 호출: super()
class P_Class:
    def __init__(self, pNum1, pNum2):
        print('[P_Class] __init__() called')
        self.pNum1 = pNum1
        self.pNum2 = pNum2


class C_Class(P_Class):
    def __init__(self, cNum1, cNum2):
        print('[C_Class] __init__() called')
		
        #P_Class.__init__(self, cNum1, cNum2)
        super().__init__(cNum1, cNum2)  #상위 클래스로 올라가서 초기화
  
		self.cNum1 = cNum1
        self.cNum2 = cNum2
cls = C_Class(10, 20)
>>>
[C_Class] __init__() called
[P_Class] __init__() called

추상 클래스

: 상위 클래스에서 하위 클래서에 메소드 구현을 강요

from abc import ABCMeta
from abc import abstractmethod

class AirPlane(metaclass=ABCMeta):
    @abstractmethod
    def flight(self):
        pass

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

//구현하지 않으면: TypeError: Can't instantiate abstract class Airliner with abstract method flight

📌 예외

예외: 문법적인 문제는 없으나 실행 중 발생하는 예상하지 못한 문제.

  • 예외 처리: try~except
n1 = 10; n2 = 0
try: 
	print(n1 / n2)
except: # try가 실패할 경우 
	print('예외 발생')

>>>
예외 발생
  • try~except~else: 예외가 발생하지 않으면 else 실행

  • finally: 예외 발생과 상관없이 항상 실행.

try:
    inputData = input('input number: ')
    numInt = int(inputData)

except:
    print('exception raise')
    numInt = 0

else:
    if numInt % 2 == 0:
        print('inputData is even number')
    else:
        print('inputData is odd number')

finally:
    print(f'inputData: {inputData}')
  • Exception: 예외 담당 클래스
n1 = 10; n2 = 0
try:
	print(n1 / n2)
except Exception as e:
    print(f'exception: {e}')

>>>
exception: division by zero
  • raise: 예외를 발생시키는 키워드
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)
  • 사용자 예외 클래스: Exception 클래스 상속해서 만들기
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)

📌 텍스트 파일

  • 기본 함수: open(), read(), write(), close()
file = open('C:/pythonTxt/test.txt', 'w')  #w: 쓰기 모드

strCnt = file.write('Hello world~')
print(f'strCnt: {strCnt}')

file.close()
  • 파일 모드
    • 'w': 쓰기 전용(파일이 있으면 덮어씌움)
    • 'a': 쓰기 전용(파일이 있으면 덧붙임)
    • 'x': 쓰기 전용(파일이 있으면 에러 발생)
    • 'r': 읽기 전용(파일이 없으면 에러 발생)
  • with ~ as 문을 이용해서 파일 닫기(close) 생략
file = open(uri + '5_037.txt', 'a')
file.write('python study')
file.close()
==
with open(uri + '5_037.txt', 'a') as f:
	f.write('python study')
  • 실습
import random
uri = 'C:/pythonTxt/'

def writeNumbers(nums):
    for idx, num in enumerate(nums):
        with open(uri + 'lotto.txt', 'a') as f:
            if idx < (len(nums) - 2):    #','
                f.write(str(nums) + ', ')
            elif idx == (len(nums) - 2):
                f.write(str(num))           #맨 마지막에 ',' 안 찍히게
            elif idx == (len(nums) - 1):
                f.write('\n')
                f.write('bonus: ' + str(num))
                f.write('\n')

rNums = random.sample(range(1, 46), 7)
print(f'rNums: {rNums}')

writeNumbers(rNums)
>>>
[41, 37, 39, 16, 31, 13, 19], [41, 37, 39, 16, 31, 13, 19], [41, 37, 39, 16, 31, 13, 19], [41, 37, 39, 16, 31, 13, 19], [41, 37, 39, 16, 31, 13, 19], 13
bonus: 19

출력이 이상함 -> 8행에 num을 nums로 오타낸 것 발견
고치니까 제대로 돌아갔다

>>>
8, 27, 38, 45, 26, 21
bonus: 14
  • writelines(): list 또는 tuple 데이터를 파일에 쓰기 위한 함수.

  • readlines(): 파일의 모든 데이터를 읽어서 리스트로 반환

  • readline(): 한 행을 읽어서 문자열로 반환

0개의 댓글