exceptions : 예외
파이썬에서 예외 사항이란 의도하지 않는 에러가 일어나는 상황이다.
>>> list = [1, 2, 3, 4] >>> list[4] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range
리스트 요소의 수가 4개 밖에 없는데 5번째 요소를 indexing하게 되면 IndexError가 일어난다.
이러한 exception이 발생하지 않도록 코드를 구현하는 것이 가장 좋겠지만, 현실적으로 항상 가능한 것은 아니다.
exception이 발생하면, 발생한 코드 위치에서 다음 코드들이 실행되지 않고 곧바로 프로그램이 종료된다.
try:
문장1
문장2
...
문장N
except Exception:
exception이 났을 경우 실행할 예외 처리코드
finally:
Exception 여부와 상관없이 항상 마지막에 실행되는 코드
try.. except..
구문을 사용해 실행한다.def exception_handling(index):
list = [1, 2, 3, 4]
element = 0
try:
element = list[index]
print("exception이 발생하지 않았습니다.")
except:
print("exception이 발생했습니다!")
element = -1
finally:
print("이 문장은 exception 발생 여부와 상관없이 무조건 실행됩니다")
return element
def 클래스이름:
속성 = 값
class Person:
bag = []
def put_bag(self, stuff):
self.bag.append(stuff)
hyerim = Person()
hyerim.put_bag('아이패드')
tom = Person()
tom.put_bag('맥북')
print(hyerim.bag)
print(tom.bag)
['아이패드', '맥북']
['아이패드', '맥북']
사진 출처 - 파이썬 코딩 도장
class Person:
bag = []
def put_bag(self, stuff):
self.bag.append(stuff)
class Person:
bag = []
def put_bag(self, stuff):
Person.bag.append(stuff)
사진 출처 - 파이썬 코딩 도장
class Person:
#class 속성
#bag = []
def __init__(self):
self.bag = []
def put_bag(self, stuff):
self.bag.append(stuff)
hyerim = Person()
hyerim.put_bag('아이패드')
tom = Person()
tom.put_bag('맥북')
print(hyerim.bag)
print(tom.bag)
['아이패드'] ['맥북']
def 클래스이름:
__속성 = 값
class SecretItem:
__item_secret = '반지' #비공개 클래스 속성
def take_item(self):
print(SecretItem.__item_secret) #클래스 안에서만 접근할 수 있음
thief = SecretItem()
thief.take_item() #'반지'
print(thief.__item_secret) #클래스 바깥에서는 접근할 수 없음
반지 Traceback (most recent call last): File "class2.py", line 10, in <module> print(thief.__item_secret) #클래스 바깥에서는 접근할 수 없음 AttributeError: 'SecretItem' object has no attribute '__item_secret'