클래스 문법
>>> class Singer: # 가수를 정의하겠느니라…
... def sing(self): # 노래하기 메서드
... return "Lalala~"
...
>>> taeji = Singer() # 태지를 만들어랏!
>>> taeji.sing() # 노래 한 곡 부탁해요~
'Lalala~'
여기에서, taeju는 인스턴스이다.
인스턴스명 = 클래스()
변수와 메서드
변수 strength, dexterity, vitality, energy
메서드 attack()
class Amazon:
strength = 20
dexterity = 25
vitality = 20
energy = 15
def attack(self):
return 'Jab!!!'
self
그 클래스의 객체를 가리킴
메서드를 정의할 때는 항상 self라는 인자를 써주어야함
사용 예시)
def exercise(self):
self.strength += 2
self.dexterity += 3
self.vitality += 1
상속
어떤 클래스가 다른 클래스의 성질을 물려받는 것
보통사람 클래스
class Person:
# 눈 두 개, 코 하나, 입 하나...
eyes = 2
nose = 1
mouth = 1
ears = 2
arms = 2
legs = 2
# 먹고 자고 이야기하고...
def eat(self):
print '얌냠...'
def sleep(self):
print '쿨쿨...'
def talk(self):
print '주절주절...'
학생 클래스 => 보통사람 클래스를 상속 받음
class Student(Person): # Person 클래스를 상속받음
def study(self):
print '열공열공...'
학생 클래스는 보통 사람 클래스에 접근가능
따라서
>>> lee = Person()
>>> lee.mouth
1
>>> lee.talk()
주절주절...
>>> kim = Student()
>>> kim.mouth
1
>>> kim.talk()
주절주절...
객체 속의 객체
냉장고 클래스, 음식 클래스를 만든다
class Fridge:
def __init__(self):
self.isOpened = False
self.foods = []
def open(self):
self.isOpened = True
print '냉장고 문을 열었어요...'
def put(self, thing):
if self.isOpened:
self.foods.append(thing)
print '냉장고 속에 음식이 들어갔네...'
else:
print '냉장고 문이 닫혀있어서 못넣겠어요...'
def close(self):
self.isOpened = False
print '냉장고 문을 닫았어요...'
class Food:
pass
냉장고 클래스 f와 음식 클래스 apple과 elephant를 만듬
>>> import fridge
>>> f = fridge.Fridge()
>>> apple = fridge.Food()
>>> elephant = fridge.Food()
냉장고 클래스 객체 f를 사용하여 문을열고 음식을 넣음
>>> f.open()
>>> f.put(apple)
>>> f.put(elephant)
객체 속의 객체를 넣어준 결과
>>> f.foods
[<fridge.Food instance at 007924AC>, <fridge.Food instance at 0079153C>]
특별한 메서드
(1) init 메서드 (초기화)
초기화 메소드
class Book:
def setData(self, title, price, author):
self.title = title
self.price = price
self.author = author
def printData(self):
print '제목 : ', self.title
print '가격 : ', self.price
print '저자 : ', self.author
def __init__(self): //초기화 메서드
print '책 객체를 새로 만들었어요~'
객체를 만들면 초기화 메서드는 자동으로 호출
>>> import bookstore
>>> b = bookstore.Book()
책 객체를 새로 만들었어요~
초기화 메서드를 이용하여 다른 메서드로 값을 넘겨줄 수도 있음
초기화 메서드 수정
def __init__(self, title, price, author):
self.setData(title, price, author)
print '책 객체를 새로 만들었어요~'
실행 결과)
>>> reload(bookstore)
>>> b2 = bookstore.Book('내가 먹었지롱', '200원', '미니')
책 객체를 새로 만들었어요~
(2) del 메서드 (소멸자)
소멸자로, 객체가 없어질 때 호출되는 메서드
(3) repr 메서드 (프린팅)
printData와 같은 메서드를 호출하는 대신, 파이썬의 기본문인 print 문을 사용해서 책 제목 출력
def __repr__(self):
return self.title
실행결과
>>> b3 = bookstore.Book('나두 좀 줘', '100원', '쥐벼룩')
책 객체를 새로 만들었어요~
>>> print b3
나두 좀 줘
(4) add 메서드 (덧셈)
두 개의 객체 self와 other를 인자로 받아서 그 둘의 넓이를 더한 값을 돌려주는 일
>>> a = shape.Shape()
>>> a.area = 20
>>> b = shape.Shape()
>>> b.area = 10
>>> a + b
30
(5) cmp 메서드 (비교)
두 개의 객체를 비교하는 비교 연산자(<, >, ==)를 쓸 수 있도록 해주는 메서드
def __cmp__(self, other):
if self.area < other.area :
return -1
elif self.area == other.area :
return 0
else :
return 1
프로그래머의 의도와 동떨어진 상황이 발생하는 것을 예외(exception)라고 해서, 예외가 발생하면 어떤 조치를 취할 것인지 정해주는 것
예시)
>>> def f(a, b):
... try:
... if a and b:
... return (a * b) + (a / b)
... elif a:
... return '불능'
... else:
... return '부정'
... except:
... return '똑 바로 살아라'