- 클래스는 객체의 구조와 행동을 정의
- 클래스를 기반으로 생성된 객체는 인스턴스(instance)라고 부름
- 같은 클래스의 여러 인스턴스는 같은 특성을 가지면서 각각 독립된 상태를 유지
class 클래스명(베이스 클래스): def 메서드명(인수1, 인수2,....): 메서드에서 실행할 코드 return 반환값
- 베이스 클래스를 지정하면 지정한 베이스 클래스의 특성을 상속해 서브 클래스를 정의할 수 있음
- 베이스 클래스를 지정할 때는 클래스 선언문의 매개변수를 생략할 수 있으며, 생략하면 object 클래스를 상속함
- 메서드(method)란 클래스에 종속된 함수를 의미
class Page:
def __init__(self, num, content):
self.num = num
self.content = content
def output(self):
return f'{self.content}
# 클래스 객체 Page가 정의됨
Page
__main__.Page # 출력값
- 인스턴스는 클래스 정의의 내용에 기술된 메서드나 변수를 가지고 있음
- 인스턴스가 가진 메서드를 인스턴스 메서드라고 부름
- 인스턴스 메서드에서는 그 처리 중에 인스턴스 자신에게 접속할 수 있음
- 인스턴스가 가진 인스턴스 변수는 각각 인스턴스 고유의 독립 데이터임
- 클래스 이름을 호출하면 인스턴스를 생성 할 수 있는데, 이를 인스턴스화(instantation)라고도 부름
- 클래스 객체에 전달되는 인수를 init() 메서드에 전달하여 인스턴스 초기화에 이용
title = Page(0, "Hi!!!")
# isinstance를 이용하여 Page 클래스의 인스턴인지 확인
isinstance(title, Page)
# dir를 사용하여 인스턴스가 가진 속성을 확인
dir(title)
['__class__', # 출력값
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'content',
'num',
'output']
외부에서 클래스 내부 변수를 참조하기 위한 함수
getter, setter 방식이 존재
- 예제
class Book: def __init__(self, raw_price): if raw_price < 0 : raise ValueError('price must be positive') self.raw_price = raw_price self._discounts = 0 @property def discounts(self): return self._discounts @discounts.setter def discounts(self, value): if value < 0 or 100 < value: raise ValueError('discounts must be between 0 and 100') self._discounts = value @property def price(self): multi = 100 - self._discounts return int(self.raw_price * multi / 100)