4. 클래스 외

4.1. 클래스

- 클래스 선언

class Cookie:
	pass
    
a = Cookie()

 

- 메소드: 클래스의 함수

class FourCal:
	def setdata(self, first, second):
    	self.first = first
        self.second = second
        
a = FourCal()
a.setdata(3, 6)

print(a.first)

 

- 생성자: 위의 setdata는 객체에 초기값으로 설정해주는게 안전하므로 생성자에 정의할 수 있다.

class FourCal:
	def __init__(self, first, second):
    	self.first = first
        self.second = second
        
    def add(self):
    	result = self.first + self.second
        return result
        
a = FourCal(4, 2)
print(a.add())

 

- 클래스의 상속

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

* 메소드 오버라이딩 시 메소드의 이름을 가지고 메소드 구분을 한다. 즉 메소드 명이 같으면 파라미터 개수가 달라도 마지막 정의된 메소드로 오버라이딩 된다.

 

- 클래스 변수

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

* java의 static 변수와 같다.

 

4.2. 모듈

- 모듈 만들기

# mod1.py
PI = 3.141592

class Math:
	def solv(self, r):
    	return PI * (r ** 2)

def add(a, b):
	return a + b
    
if __name__ == "__main__": # 직접 파일 실행시 __name__ 이 "__main__" 이며, import 시 "mod1" 이다.
	print(add(1, 4))

 

- 모듈 불러오기

# main.py

import mod1
'''
from mod1 import add # add(3, 4) 와 같이 호출한다.
from mod1 import Math # math = Math() 와 같이 호출한다.
from mod1 import add, sub # 여러개인 경우 *
'''
print(mod1.add(3, 4))

* import 는

1. 파이썬 라이브러리가 저장된 디렉토리,

2. 현재 디렉토리에 있는 모듈,

3. sys.path.append([모듈이 저장된 디렉토리]) 설정 후의 모듈

4. export로 PYTHONPATH=[모듈이 저장된 디렉토리] 환경 변수 설정 후의 모듈

만 불러온다.

 

- 모듈에 별칭 주기: as

 

4.3. 패키지

 - 패키지와 모듈: 패키지는 디렉토리, 모듈은 파이썬 파일이라 할 수 있다.

 

- 패키지로 인식되고 싶은 디렉토리에 __init__.py 파일을 생성해 두며,

__init__.py 모듈은 해당 파일이 속한 디렉토리를 import 해 와서 사용 할 수 있다.

 

- 패키지 구조를 아래와 같이 구성할 때 game package를 참조하기 위해서는 export PYTHONPATH=C:/doit 을 통해 환경변수를 세팅해줘야 한다.

C:/doit/game/__init__.py
C:/doit/game/sound/__init__.py
C:/doit/game/sound/echo.py
C:/doit/game/graphic/__init__.py
C:/doit/game/graphic/render.py

 

- 패키지 안의 함수 실행하기

* import 시 실행 파일이 실행되는 위치를 기준으로 패키지 경로를 맞춘다.

# main.py

# echo 모듈 import
''' 방법1
import game.sound.echo
game.sound.echo.echo_test()
'''

''' 방법2
from game.sound import echo 
# from 패키지 import 모듈 시 * 로 사용하려면, __init__.py 에 __all__ = ['echo'] 를 정의한다.
echo.echo_test()
'''

# echo_test 함수 import
'''
from game.sound.echo import echo_test
echo_test()
'''

import시 __init__.py 외에는 최소 import 해야 하는 모듈까지 import 경로를 명시해주어야 한다.

 

- from a.b.c import d 또는 import a.b.c 시 a, b, c 는 반드시 모듈 또는 패키지여야 한다.

 

- relative 패키지: render.py 모듈이 echo.py 모듈을 사용하고 싶을 때

# render.py
from game.sound.echo import echo_test
# 또는 from ..sound.echo import echo_test
def render_test():
	print("render")
    echo_test()
    
# main.py
from game.graphic.render import render_test
render_test()

 

4.4. 예외 처리

- 오류 예외처리 기법: try .. except

# 방법1: try, except만 쓰는 방법
try:
	4 / 0
except:
	print("Can NOT divided by 0")
    
# 방법2: 발생 오류를 포함한 except 문
try:
	a = [1, 2]
    print(a[3])
	4 / 0
except ZeroDivisionError as e: # 여러개의 Exception 은 (ZeroDivisionError, IndexError) 와 같이 표현한다.
	print(e)
except IndexError as e:
	print(e)

 

- try .. finally

try:
	f = open("없는 파일", 'r')
finally:
	f.close() # FileNotFoundError 던지고, finally 구문을 실행한다.

 

- try .. except .. else

try:
	age = int(input("나이를 입력하세요: "))
except:
	print("입력이 정확하지 않습니다.")
else:
	if age <= 18:
    	print("미성년자는 출입금지입니다.")
    else:
    	print("환영합니다.")

 

오류 일부러 발생시키기: raise

class Bird:
	def fly(self):
    	raise NotImplementedError # 상속시 반드시 구현하도록 한다.

class Eagle(Bird):
	pass
    
eagle = Eagle()
eagle.fly() # NotImplementedError 가 발생한다.

 

- 예외 만들기

class MyError(Exception):
	def __str__(self):
    	return "허용되지 않는 별명입니다."
    
def say_nick(nick):
	if nick == "바보":
    	raise MyError()
    print(nick)
    
say_nick("바보") # MyError 가 발생하며 에러메세지는 __str__ 로 구현된다.

 

4.5. 내장 함수

abs(-1.2) # 1.2

max([1, 2, 3]) # 3
min([1, 2, 3]) # 1

hex(234) # 10진수 -> 16진수 문자열로 변환
oct(34) # 10진수 -> 8진수 문자열로 변환
int('0x1a', 16) # 16진수 -> 10진수로 변환

round(4.6) # 5, 반올림
round(5.678, 2) # 5.68, 소수 둣째짜리까지만 반올림하여 표시

sorted([3, 1, 2]) # [1, 2, 3]
sum([1, 2, 3])

zip([1, 2, 3], [4, 5, 6]) # 동일한 개수로 이루어진 자료형을 묶어준다.
'''
	list(zip([1, 2, 3], [4, 5, 6])) # [(1, 4), (2, 5), (3, 6)]
'''

range(1, 10, 2) # 시작, 끝, 숫자 사이 거리 순으로 인수를 받는다.

enumerate([반복 가능한 자료형]) # i, 내용 의 enumerate 객체
'''
	for i, name in enumerate(['body', 'foo', 'bar']):
    	print(i, name)
'''

filter([함수], [반복 가능한 자료형])
'''
	list(filter(lambda x: x>0, [1, -3, 2, 0, -5, 6]))
'''

map([함수], [반복 가능한 자료형])
'''
	list(map(lambda x: x*2, [1, 2, 3, 4]))
'''

isinstance(a, Person) # 인스턴스, 클래스를 인수로 받아 판단 결과를 True, False 로 돌려준다.

divmod(7, 3) # ([몫], [나머지])

eval('1+2') # 실행 가능한 문자열을 실행한 결과

 

4.6. 라이브러리

- sys

import sys
print(sys.argv) # 명령 프롬프트 창에서 python3 argv_test.py you need python 시 ['argv_test.py', 'you', 'need', 'python']과 같이 출력된다.
sys.exit()
sys.path # 파이썬 모듈들이 저장된 위치이다. ['', '/Users/user/vsc-workspace/python/_5_add_wing_of_python/_5_3_package', ... ]
sys.path.append("C:/doit/mymod")

 

- os

import os
os.environ # 현재 시스템의 환경변수 값이다. environ({'USER': 'user', '__CFBundleIdentifier': 'com.microsoft.VSCode', ...})
os.environ['PATH']
os.chdir("C:\WINDOWS") # 현재 디렉토리 위치 변경
os.getcwd() # 현재 디렉토리의 위치
os.system("ls") # 시스템 명령어 실행
f = os.popen("ls") # 시스템 명령어를 실행한 결과값을 읽기 모드 형태의 파일 객체로 돌려준다. print(f.read()) 와 같이 내용을 볼 수 있다.

* 하위 디렉터리 검색하기

import os
filenames = os.listdir(dirname) # 인자로 받은 디렉토리의 ls 값을 iterable 자료형으로 돌려준다.
full_filename = os.path.join(dirname, filename) # 인자로 받은 디렉토리와 파일이름 값을 경로 구분자를 사용하여 join한다.
ext = os.path.splitext(full_filename)[-1] # 해당 파일의 확장자를를 가져온다.
os.path.isdir(full_filename)

* 하위 디렉터리 검색을 쉽게: os.walk

import os
for (path, dirs, files) in os.walk("c:/"):
	for filename in files:
    	ext = os.path.splitext()[-1]
        if ext == ".py":
        	print("%s%s" % (path, filename))

 

- shutil: shutil.copy("src.txt", "dst.txt")

- glob: 디렉토리에 있는 파일 찾아 리스트로 만들기

import glob
glob.glob("c:/doit/mark*") # ['c:/doit\\marks1.py', 'c:/doit\\marks2.py', 'c:/doit\\marks3.py']

 

- time

import time
time.time() # UTC 를 사용하여 기준시부터 현재 시간까지를 초 단위로 돌려준다. 988458015.73417199
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.asctime(time.localtime(time.time())) # 'Sat Apr 28 20:50:20 2001'
time.ctime() # 'Sat Apr 28 20:56:31 2001'
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
time.strftime("%Y-%m-%d %H:%M:%S")
time.sleep(0.3) # 주워진 초만큼 시간 간격을 둔다.

* 시간에 관계된 것을 표현하는 포맷 코드

분류 포맷코드
%Y, %y 2001, 01
%m, %B, %b [01,12], January, Jan
%d [01,31]
%H, %l, %p [00,23], [01,12], AM
%M [01, 59]
%S [00, 59]
요일 %w, %A, %a [0(일요일),6], Monday, Mon
포맷팅 %c, %x, %X 06/01/01 17:22:21, 06/01/01, 17:22:21

 

- random

import random
random.random() # [0.0, 1.0) 범위의 실수인 난수 생성. 0.53840103305098674
random.ranint(1, 10) # [1, 10] 범위의 정수인 난수 생성. 6
random.choice(data) # data 리스트에서 무작위로 하나를 선택해서 돌려준다.
random.shuffle(data) # data 리스트의 항목을 무작위로 섞는다.

 

- webbrowser

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

 

- threading

# thread_test.py
import time
import threading # 스레드를 생성하기 위해 threading 모듈이 필요하다.

def long_task():
	for i in range(5):
    	time.sleep(1)
        print("working:%s\n" % i)
        
print("Start")

threads = []
for i in range(5):
	t = threading.Thread(target=long_task) # 스레드를 생성한다.
    threads.append(t)
    
for t in threads:
	t.start() # 스레드를 실행한다.
    
for t in threads:
	t.join() # join으로 다음 코드는 스레드가 종료된 후 실행된다.
    
print("End")
블로그 이미지

uchacha

개발자 일지

,