본문 바로가기
Programming/PYTHON

파이썬 날개 달기

by akter 2022. 3. 4.

파이썬 프로그래밍의 핵심, 클래스

 

클래스

반복되는 변수 & 메소드(함수)를 미리 정해놓은 틀(설계도)

 

 

클래스는 도대체 왜 필요한가?

result = 0
def add(num):
    global result
    result += num
    return result
    
print(add(3))
print(add(4))

 

 

두 개의 계산기

result1 = 0
result2 = 0

def add1(num):
    global result1
    result += num
    return result1
    
def add2(num):
    global result2
    result2 += num
    return result2
    
print(add1(3))
print(add1(4))
print(add2(3))
print(add2(7))

 

 

클래스를 이용한 계산기

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))

 

 

클래스 비유

과자 틀(클래스), 과자(객체)

과자 틀(클래스)과 이 틀로 찍어 만든 과자(객체)

 

사칙연산 클래스 1

class FourCal:
	pass
a = FourCal()
print(type(a))
<class '__main__.FourCal'>

 

 

사칙연산 클래스 2

a.setdata(4, 2)
class FourCal:
	def setdata(self, first, second):
    	self.first = first
        self.second = second
        
a = FourCal()
a.setdata(4, 2)

print(a.first)
print(a.second)

 

 

사칙연산 클래스 3

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

 

 

클래스의 상속

class MoreFourCal(FourCal):
	pass
a = MoreFourCal(4, 2)
a.add()
6

 

 

클래스의 상속 2 - 메서드 추가

class MoreFourCal(FourCal):
	def pow(self):
    	result = self.first ** self.second
        return result
a = MoreFourCal(4, 2)
a.pow()
16

 

 

메서드 오버라이딩

class SafeFourCal(FourCal):
	def div(self):
    	if self.second == 0:
        	return 0
        else:
        	return self.first / self.second

 

 

클래스 변수, 객체 변수

class Family:
	lastname = "김"
    
Family.lastname = "박"
print(Family.lastname)

a = Family()
b = Family()
print(a.lastname)
pritn(b.lastname)

 


모듈

 

모듈이란

미리 만들어 놓은 .py 파일(함수, 변수, 클래스)

#mod1.py
def add(a, b):
	return a + b
import mod1
print(mod1.add(1, 2))
from mod1 import add
print(mod1.add(1, 2))

 

 

if __name__ == "__main__":의 의미

#mod1.py
def add(a, b):
	return a + b
    
def sub(a, b):
	return a - b
    
if __name__ == "__main__":
	print(add(1, 4))
    pritn(add(4, 2))

 

 

sys.path.append

import sys
print(sys.path)
['', 'C:\\Windows\\SYSTEM32\\python35.zip',
'c:\\Python35\\DLLs',
'c:\\Python35\\lib', 'c:\\Python35',
'c:\\Python35\\lib\\site-packages']
import sys
sys.path.append("C:\\python_study\\subFolder")
import mod2
print(mod2.add(3, 4))

 


패키지

패키지 = 라이브러리

 

패키지란?

모듈 여러 개 모아놓은 것

 

가상의 game 패키지 예

game/
	__init__.py
    sound/
    	__init__.py
        echo.py
    graphic/
    	__init__.py
        render.py

 

 

테스트를 위해 패키지 만들기

C:/python study/game/__init__.py
C:/python study/game/sound/__init__.py
C:/python study/game/sound/echo.py
C:/python study/game/graphic/__init__.py
C:/python study/game/graphic/render.py
# echo.py
def echo test():
	print("echo")
# render.py
def render_test():
	print("render")

 

 

패키지 안의 함수 실행하기

import game.sound.echo
game.sound.echo.echo_test()
echo
from game.sound import echo
echo.echo_test()
echo
from game.sound.echo import echo_test
echo_test()
echo

 

 

__all__

from game.sound import *
echo.echo_test()

Traceback (most recent call last):
	File "<stdin>", line 1, in <module>
NameError: name 'echo' is not defined
# C:/python study/game/sound/__init__.py
__all__ = ['echo']

 

 

relative 패키지

# render.py
from ..sound.echo import echo_test

def render_test():
    print("render")
    echo_test()

 

 


예외 처리

오류가 발생했을 때 어떻게 할지 정하는 것

 

try: #오류가 발생할 수 있는 구문

except Exception as e: #오류발생

else: #오류 발생하지 않음

finally: #무조건 마지막에 실행

 

try, except문

try:
	...
except [발생 오류[as 오류 메세지 변수]]:
	...
try:
	4 / 0
except ZeroDrivisionError as e:
	print(e)

 

 

try .. else

try:
	f = open(foo.txt', 'r')
except FileNotFoundError as e:
	print(str(e))
else:
	data = f.read()
    print(data)
    f.close()

 

 

try .. finally

f = open('foo.txt', 'w')
try:
	# 무언가를 수행한다.
finally:
	f.close()
f = open('foo.txt', 'w')
try:
    # 무언가를 수행한다.
    data = f.read()
    print(data)
except Exception as e:
	print(e)
finally:
	f.close()

 

 

여러 개의 오류 처리하기

try:
    a = [1, 2]
    print(a[3])
    4 / 0
except ZeroDivisionError:
	print("0으로 나눌 수 없습니다.")
except IndexError:
	print("인덱싱할 수 없습니다")

 

 

오류 회피하기

try:
	f = open("나없는파일", 'r')
except FileNotFoundError:
	pass

 

 

오류를 일부러 발생시키기

class Bird:
    def fly(self):
    	raise NotImplementedError
class Eagle(Bird):
    def fly(self):
    	print("very fast")
        
eagle = Eagle()
eagle.fly()

 

 


내장함수

파이썬에서 기본적으로 포함하고 있는 함수

ex) print(), type()

 

abs => 절대값

>>> abs(3)
3
>>> abs(-3)
3
>>> abs(-1.2)
1.2

 

 

all => 모두 참인지 검사

>>> all([1, 2, 3])
True
>>> all(1, 2, 3, 0])
False

 

 

any => 하나라도 참이 있는가?

>>> any([1, 2, 3, 0])
True
>>> any([0, ""])
False

 

 

chr => ASCII 코드를 입력받아 문자 출력

>>> chr(97)
'a'
>>> chr(48)
'0'

 

* ASCII(아스키 코드) = 0~127 사이의 숫자를 각 문자에 대응

 

dir => 자체적으로 가지고 있는 변수나 함수를 보여줌

>>> dir([1, 2, 3])
['append', 'count', 'extend', 'index', 'insert', 'pop', ...]
>>> dir({'1' : 'a'})
['clear', 'copy', 'get', 'has_key', 'items', 'keys', ...]

 

 

divmod => 몫과 나머지를 튜플 형태로 돌려줌

>>> divmod(7, 3)
(2, 1)
>>> divmod(1.3, 0.2)
(6.0 0.09999999999999998)

 

 

enumerate => 열거하다

for i, name in enumerate(['body', 'foo', 'bar']):
	print(i, name)
    
0 body
1 foo
2 bar

 

 

eval => 실행 후 결과값을 돌려줌

>>> eval('1 + 2')
3
>>> eval("'hi' + 'a'")
'hia'
>>> eval('divmod(4, 3)')
(1, 1)

 

 

filter => 함수를 통과하여 참인 것만 돌려줌

def positive(x):
	return x > 0
    
a = list(filter(positive, [1, -3, 2, 0, -5, 6]))
print(a)
a = list(filter(lambda x: x > 0, [1, -3, 2, 0, -5, 6]))
print(a)

 

 

id => 주소 값

>>> a = 3
>>> id(3)
135072304
>>> id(a)
135072304
>>> b = a
>>> id(b)
135072304

 

 

input => 사용자 입력 받는 횟수

>>> a = input()
hi
>>> a
'hi'
>>> b = input("Enter: ")
Enter: hi

 

>>> b
'hi'

 

 

int => 10진수 정수 형태로 변환

>>> int('3')
3
>>> int(3.4)
3
>>> int('11', 2)
3
>>> int('1A', 16)
26

 

 

len => 길이

>>> len("python")
6
>>> len([1, 2, 3])
3
>>> len((1, 'a'))
2

 

 

list => 리스트로 변환

>>> list("python")
['p', 'y', 't', 'h', 'o', 'n']
>>> list((1, 2, 3))
[1, 2, 3]
>>> a = [1, 2, 3]
>>> b = list(a)
>>> b
[1, 2, 3]

 

 

map => 각 요소가 수행한 결과를 돌려줌

def two_times(x): return x * 2
a = list(map(two_times, [1, 2, 3, 4]))
print(a)
a = list(map(lambda a: a * 2, [1, 2, 3, 4]))
print(a)

 

 

max => 최대 값

>>> max([1, 2, 3])
3
>>> max("python")
'y'

 

 

min => 최소 값

>>> min([1, 2, 3])
1
>>> min("python")
'h'

 

 

open

mode 설명
w 쓰기 모드로 파일 열기
r 읽기 모드로 파일 열기
a 추가 모드로 파일 열기
b 바이너리 모드로 파일 열기
>>> f = open("binary_file", "rb")

 

 

pow => 제곱한 결과값 반환

>>> pow(2, 4)
16
>>> pow(3, 3)
27

 

 

range => 범위

>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(5, 10))
[5, 6, 7, 8, 9]
>>> list(range(1, 10, 2))
[1, 3, 5, 7, 9]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

 

 

round => 반올림

round(4.6)
>> 5
round(4.2)
>> 4

round(5.678, 2)
>> 5.68

 

 

sorted => 정렬

>>> sorted([3, 1, 2])
[1, 2, 3]
>>> sorted(['a', 'c', 'b'])
['a', 'b', 'c']
>>> sorted("zero")
['e', 'o', 'r', 'z']
>>> sorted((3, 1, 2))
[1, 2, 3]

 

 

str => 문자열 반환

>>> str(3)
'3'
>>> str('hi')
'hi'
>>> str('hi'.upper())
"HI"

 

 

tuple => 튜플 반환

>>> tuple("abc")
('a', 'b', 'c')
>>> tuple([1, 2, 3])
(1, 2, 3)
>>> tuple((1, 2, 3))
(1, 2, 3)

 

 

type => 타입을 출력

>>> type("abc")
<class 'str'>
>>> type([ ])
<class 'list'>
>>> type(open("test", 'w'))
<class '_io.TextIOWrapper'>

 

 

zip => 자료형을 묶어주는 역할

>>> list(zip([1, 2, 3], [4, 5, 6]))
[(1, 4), (2, 5), (3, 6)]
>>> list(zip([1, 2, 3], [4, 5, 6], [7, 8, 9]))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> list(zip("abc", "def"))
[('a', 'b'), ('b', 'e'), ('c', 'f')]

 

 


외장함수

라이브러리 함수, import 해서 쓰는 것

 

sys.argv

# argv_test.py
import sys
print(sys.argv)
C:/Python/Mymodules>python argv_test.py you need python
['argv_test.py', 'you', 'need', 'python']

 

 

pickle

import pickle
f = open("test.txt", 'wb')
data = {1: 'python', 2: 'you need'}
pickle.dump(data, f)
f.close()
import pickle
f = open("text.txt", 'rb')
data = pickle.load(f)
print(data)
{2: 'you need', 1: 'python'}

 

 

time

import time
print(time.time())
#1970년 1월 1일 0시 0분 0초를 기준으로 지난 시간 초
print(time.localtime(time.time()))
time.struct_time(tm_year=2013, tm_mon=5, tm_mday=21,
tm_hour=16,
	tm_min=48, tm_sec=42, tm_wday=1, tm_yday=141, tm_isdst=0)

 

 

time.sleep

#sleep.py
import time
for i in range(5):
    print(i)
    time.sleep(1)

 

 

random

import random
print(random.random())
# 0~1 사이의 난수
random.randint(1, 10)
6
data = [1, 2, 3, 4, 5]
random.shuffle(data)
data
[5, 1, 3, 4, 2]
import random
lotto = sorted(random.sample(range(1,46), 6))
print(lotto)

 

 

webbrowser

import webbrowser
webbrowser.open("http://google.com")
webbrowser.open_new("http://google.com")

 

 

 

댓글