파이썬 날개 달기
Immutable (정수,실수,문자열,튜플) → 변하지 않는 자료형
a = 1
def vartest(a):
a =a + 1
vartest(a)
print(a)
Mutable (리스트, 딕셔너리, 집합) → 변할 수 있는 자료형
b = [1,2,3]
def vartest2(b):
b = b.append(4)
vartest2(b)
print(b)
[목차]
- 클래스
- 모듈
- 패키지
- 예외 처리
- 내장 함수
- 외장 함수
클래스
클래스: 반복되는 변수 & 메서드(함수)를 미리 정해놓은 틀(설계도)
ex)
result = 0
def add(num):
global result
result += num
return result
print(add(3))
print(add(4))
→ 클래스 적용
class Calculator:
def __init__(self):
self.result = 0
def add(self,num):
self.result += num
return self.result
cal1 = Calculator()
cal2 = Calculator()
print(cal1.add(3))
print(cal1.add(4))
print(cal2.add(3))
print(cal2.add(7))
ex1)
class FourCal:
def setdata(self, first,second):
self.first = first
self.second = second
a = FourCal()
a.setdata(1,2)
print(a.first)
print(a.second)
→ 1, 2
ex2)
class FourCal:
def setdata(self, first,second):
self.first = first
self.second = second
def add(self):
result = self.first + self.second
return result
a = FourCal()
a.setdata(4,2)
print(a.add())
→ 6
생성자 (Constructor)
class FourCal:
def __init__(self,first,second):#constructor
self.first = first
self.second = second
def setdata(self, first,second):
self.first = first
self.second = second
def add(self):
result = self.first + self.second
return result
a = FourCal(1,2)
상속(Inheritance)
FourCal>MoreFourCal
class FourCal:
def __init__(self,first,second):#constructor
self.first = first
self.second = second
def setdata(self, first,second):
self.first = first
self.second = second
def add(self):
result = self.first + self.second
return result
class MoreFourCal(FourCal):
def pow(self):
result = self.first ** self.second
return result
a = MoreFourCal(4,2)
print(a.pow())
Method overriding
class FourCal:
def __init__(self,first,second):#constructor
self.first = first
self.second = second
def setdata(self, first,second):
self.first = first
self.second = second
def add(self):
result = self.first + self.second
return result
def div(self):
result = self.first / self.second
return result
class SafeFourCal(FourCal):
def div(self):
if self.second == 0:
return 0
else:
return self.first / self.second
a = SafeFourCal(4,0)
print(a.div())
→ 0
클래스 변수, 객체 변수
class FourCal:
#클래스 변수
first = 2
second = 3
#객체 변수
def __init__(self,first,second):#constructor
self.first = first
self.second = second
def setdata(self, first,second):
self.first = first
self.second = second
def add(self):
result = self.first + self.second
return result
def div(self):
result = self.first / self.second
return result
class SafeFourCal(FourCal):
def div(self):
if self.second == 0:
return 0
else:
return self.first / self.second
a = SafeFourCal(4,0)
print(a.div())
모듈
모듈이란?
미리 만들어 놓은 .py 파일 (함수,변수,클래스)
- mod1.py
#mod1.py
def add(a,b):
return a+b
- mod1.py 모듈 활용
import mod1
print(mod1.add(1,2))
from mod1 import add
print(add(1,2))
ex2)
- mod1.py
#mod1.py
def add(a,b):
return a+b
def sub(a,b):
return a-b
print(add(1,4))
print(add(4,2))
- import만
import mod1
→ 5, 6
바로 실행을 안하려면
- mod1.py
#mod1.py
def add(a,b):
return a+b
def sub(a,b):
return a-b
if __name__ == "__main__":
print(add(1,4))
print(add(4,2))
sys.path.append
import sys
sys.path.append("C:\\jocoding\\subFolder")
import mod1
print(mod1.add(3,4))
패키지
패키지란?
모듈 여러 개를 모아놓은 것
- 가상의 game 패키지 예
game/
__init__.py
sound/
__init__.py
echo.py
graphic/
__init__.py
render.py
불러오려면?
ex1)
import game.sound.echo
game.sound.echo.echo_test()
ex2)
from game.sound import echo
echo.echo_tset()
ex3)
from game.sound.echo import echo_test as e
e()
__all__
from game.sound import * #전부 불러와라
echo.echo_test()
sound 폴더 내부에 __init__.py
__all__ = ['echo','echo2']
relative 패키지
# .. 은 이전 폴더로 돌아가라는 의미
from ..sound.echo import echo_test
예외처리
예외처리란?
오류가 발생했을 때 어떻게 할지 정하는 것
try, except 문
try:
#오류가 발생할 수 있는 구문
except Exception as e:
#오류가 발생했을 때 실행
else:
#오류 발생하지 않았을 때 실행
finally:
#무조건 마지막에 실행
ex)
try:
4/0
except ZeroDivisionError as e:
print(e)
try, else 문
try:
f = open('none','r')
except FileNotFoundError as e:
print(str(e))
else:
data = f.read()
print(data)
f.close()
오류 일부러 발생시키기
raise NotImplementedError
내장 함수
내장함수란?
파이썬에서 기본적으로 포함하고 있는 함수
ex)
- abs
- all
- any
- chr
- dir
- divmod
- enumerate
- eval
- filter
- hex
- id
- input
- int
- isinstance
- len
- list
- map
- max
- min
- oct
- open
- ord
- pow
- range
- round
- sorted
- str
- sum
- tuple
- type
- zip
외장함수
표준 라이브러리
외부 라이브러리
※ 해당 게시글은 개인 학습의 목적으로, 아래 강의를 수강한 후 정리한 학습노트입니다.
https://www.youtube.com/watch?v=YrPu4hEs58s&list=PLU9-uwewPMe2AX9o9hFgv-nRvOcBdzvP5&index=8
'Python 프로그래밍 > 기초 문법' 카테고리의 다른 글
[점프 투 파이썬] 7강: 정규표현식이란? 파이썬 정규표현식의 기초와 활용 (0) | 2024.06.12 |
---|---|
[점프 투 파이썬] 6강: 파이썬 프로그래밍, 어떻게 시작해야 할까? (0) | 2024.06.12 |
[점프 투 파이썬] 4강: 파이썬의 입출력 (0) | 2024.06.11 |
[점프 투 파이썬] 3강: 프로그램의 구조를 쌓는다! 제어문 (0) | 2024.06.10 |
[점프 투 파이썬] 2강: 파이썬 프로그래밍의 기초, 자료형(2) (0) | 2024.06.09 |