티스토리 뷰

Modules (파일 분리)

자주 사용하는 함수 및 클래스를 
하나의 파일 형태로 모아두는 것을 모듈화한다고 한다.


위와같이 print_helper.py 와 /dictionary/dictionary_helper.py 를 만들었다면

아래와 같이 import 시킬 수 있다.

import print_helper
from dictionary import dictionary_helper



Exceptions

try-except-finally

while True:
try:
number = int(input('What is your favorite number?\n'))
print(23 / number)
break
except ValueError:
print('Make sure and enter a number')
except Exception as e: # -> except: 와 동일
print(e)
break
finally:
print('loop complete')

finally 는 exception 이 나던 말던 실행되는 구문이다.


try-except-else

else 절은 예외가 발생하지 않았을 때 실행되는 구문이다.

else 는 모든 except 절의 마지막에 하나만 들어갈 수 있다.

try:
number = int(input('What is your favorite number?\n'))
print(23 / number)
break
except ValueError:
print('Make sure and enter a number')
except ZeroDivisionError:
print('Don\'t pick zero')
else:
print('loop complete')

raise

예외를 일부러 발생시킨다.
raise [예외] or raise[예외(데이터)] 로 발생시킬 수 있다.
try:
a = int(input('피제수를 입력하세요: '))
b = int(input('제수를 입력하세요: '))
if a <= 0 or b <= 0:
raise ArithmeticError('피제수 혹은 제수가 0 이하일 수 없습니다.') # -> raise ArithmeticError 로도 가능하다.
except ArithmeticError as e:
print('예외 발생:', e.args[0]) # -> 예외 발생: 피제수 혹은 제수가 0 이하일 수 없습니다.



Classes and Object


선언 및 사용

아래와 같이 선언하고 사용한다.
클래스명의 첫 글자는 영문 대문자여야한다.
python 에서 클래스 내부 멤버변수를 접근하기 위해선 self 가 필요하다.

class Enemy:
life = 3

def attact(self):
self.life -= 1

def checkLife(self):
if self.life <= 0:
print('Dead')
else:
print(str(self.life) + " life left")


enemy = Enemy()
enemy.attact()
enemy.checkLife() # -> 2 life left

enemy.attact()
enemy.attact()
enemy.checkLife() # -> Dead

init

생성자에 parameter 를 아래와 같이 넘길 수 있다.
특이한 점은 멤버변수를 선언하지 않아도 사용할 수 있다는 점이다.
init 에서 self.energy 를 선언하면 get_energy method 에서도 사용할 수 있다.
class Person():
def __init__(self):
print('init')


lucy = Person(); # -> init


class Archer:
def __init__(self, amount):
self.energy = amount

def get_energy(self):
return self.energy


archer = Archer(3)
print(archer.get_energy()) # -> 3

inheritance, multiple inheritance (상속, 다중상속)

class Parent():
def print_last_name(self):
print('Norman')

class Child(Parent):
def print_first_name(self):
print('Chris')

def print_last_name(self):
super().print_last_name()
print('Roberts')

child = Child()
child.print_first_name() # -> Chris
child.print_last_name() # -> Norman, Roberts
class Archer():
def move(self):
print('I am moving')


class Item():
def eat_item(self):
print('I am leveling up')


class LevelupArcher(Archer, Item):
pass # -> 추가할 메소드가 없을 때는 반드시 pass 를 해줘야한다.


lvarc = LevelupArcher()
lvarc.eat_item() # -> I am leveling up
lvarc.move() # -> I am moving

Interface 와 Abstract 처럼 사용하고 싶을 때는
클래스와 메소드에 pass 와 raise 를 이용해서 구현한다.



출처

http://creativeworks.tistory.com/m/category/Programming/Python%20Tutorials 의 20, 26 ~ 30 장
http://blog.eairship.kr/294





공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함