파이썬 클래스
- 하나의 이름 공간
- 함수(메쏘드)와 변수(멤버)를 갖는다
- 상속(inheritance)이 된다
- 연산자 중복 지원
클래스 인스턴스
- 클래스를 호출하여 만들어지는 객체
(이건 구조체..- 내 생각에는)
class Simple: # 헤더(header)
pass # 몸체(body)
인스턴스 객체의 생성
s1 = simple() # 클래스 인스턴스(구조체 변수 선언?)
s2 = simple()
s1.stack = [] # s1에만 stack=[]이 생성 클래스 인스턴스는 독립적이다.
메쏘드 정의하기
- 일반 함수 정의와 동일
- 첫 인수로 인스턴스 객체가 온다(self)
- self는 C++,Java의 this와 비슷
class MyClass:
def set(self,v):
self.value = v
def put(self):
print self.value
메쏘드 호출하기
- bound instance method
c = MyClass() # 인스턴스 생성
c.set('egg') # 메쏘드 set 호출
c.put() # 메쏘드 put 호출
egg
- unbound instance method
MyClass.set(c,'egg')
MyClass.put(c)
egg
클래스 내부에서의 메쏘드 호출
class MyClass2:
def set(self,v):
self.value = v
def incr(self):
self.set(self.value + 1)
def put(self):
print self.value
정적 메쏘드(static method, 2.2)
- 인스턴스 객체 없이 클래스에서 직접 호출할 수 있는 메쏘드
class D:
def spam(x,y): # self가 없다
print 'static method', x,y
spam = staticmethod(spam)
D.spam(1,2) # 클래스에서 직접 호출
static method 1 2
d = D()
d.spam(1,2) # 인스턴스를 통하여 호출
클래스 메쏘드(class method, 2.2)
- 첫 인수로 클래스 객체를 받는다
class c:
def spam(cls, y):
print cls,y
spam = classmethod(spam)
print C
_main_.C
C.spam(5)
_main_.C 5
TrueCrpyt,
TiSync,UOsync,AllwaySync 동기화 프로그램
포터블 프로그램
- 포터블 인터넷 브라우저(The World)
Jw broweser 즐겨찾기(설정 그대로)
포터블 오피스 계열의 프로그램
OpenOffice...
포토샵, 7-Zip 그래픽 뷰어
런쳐?
USBPRO UO lauchpro
가상 운영체제
VMware,
Virtual PC,Virtual Box # 무료
Moka5
mojopac
SLC,대용량
USBOFFICE
클래스 멤버와 인스턴스 멤버
클래스멤버
- 클래스 이름 공간에 생성
- 모든 인스턴스 객체들이 공유
인스턴스 멤버
- 인스턴스 내에서만 사용
class Var:
c_mem = 100 # 클래스 멤버 정의
def f(self):
self.i_mem = 200 # 인스턴스 멤버 정의
def g(self):
print self.i_mem
print self.c_mem
생성장와 소멸자
from time import time, ctime, sleep
class Life:
def _init_(self): # 생성자
self.birth = ctime() # 현재 시간
print 'Birthday', self.birth # 현재 시간 출력
def _del_(self): # 소멸자
print 'Deathday', ctime() # 소멸 시간 출력
mylife = Life()
print 'sleeping for 3 sec'
sleep(3) # 프로세서의 실행을 정지하는 함수
연산자 중복
class MyString:
def _init_(self,str):
self.str = str
def _div_(self.sep):
return self.str.split(sep)
m = Mystring('abcde')
m / 'c' # _div == '/'
['ab', 'de']
_coerce_
- 다른 두 자료형에 수치 자료형이 적용될 때 두 자료형을 조정해 주는 메쏘드
class MyNum:
def _init_(self,n):
self.n = n
def _coerce_(self,y):
return self.n, y
a = MyNum(10)
a + 20
30
상속(Inheritance):
- 기존의 클래스의 속성과 행동을 그대로 받아들이고 추가적으로 필요한 기능을 새로운 클래스에 덧붙이는 것
A 슈퍼 클래스
B 하위 클래스
B "is-a" A 관계
다중 상속(Multiple Inheritance)
class Person:
def _init_(self, name, phone=none):
self.name = name
self.phone = phone
def display(self):
return '<Person %s %s>' % (self.name, self.phone)
def _repr_(self):
return 'name=%s phone=%s' % (self.name, self.phone)
class Employee(Person):
def _init_(self, name, phone, position, salary):
Person._init_(self, name, phone) # 언바운드 클래스 메쏘드 호출로 호출해야 한다
self.position = position
self.salary = salary
m1 = Employee('손창희', '5520', '대리', 200)
메쏘드의 대치
메쏘드의 확장
class Employee(Person):
def _init_(self,name,phone,position,salary):
Person._init(self,name,phone)
self.positon = position
self.salary = salary
def _repr_(self):
s = Person._repr_(self)
return '%s pos=%s sal=%s' % (s, self.position, self.salary) # 메쏘드 확장
상속 - 다중상속
- 클래스가 두 개 이상의 슈퍼클래스로 부터 상속 받는 것
class Employee(Person, Job)
def _init_(self, name, phone, position, salary):
Person._init_(self,name,phone) # 언바운드 클래스 메써드 호출
Job._init_(self,position,salary) # 언바운드 클래스 메써드 호출
메쏘드 처리 순서
- 먼저 쓴 순서대로
다이아몬드형 다중 상속
- 메쏘드 처리 순서(MRO-method resolution order)
가상 함수
- 메쏘드의 호출이 참조되는 클래스 인스턴스에 따라서 동적으로 결정되는 함수
- 파이썬 클래스의 모든 메쏘드는 가상 함수
상속의 예
명령어 해석기의 설계
- cmd.cmd 부클래스를 하나 만드록
- 수퍼 클래스의 생성자 루틴을 수행하고,
- 프롬프트 모양을 정해주고
- 필요한 멤버를 만들어 이용하면 된다
명령어 정의하는 법
- 명령어 메쏘드 : do_명령어
- 도움말 메쏘드 : help_명령어
import sys,cmd
class MyCmd(cmd.Cmd):
def _init_(self):
cmd.Cmd._init_(self)
self.promprt = "-->"
self.list = []
def do_add(self, x):
if x and (x not in self.list):
self.list.append(x)
def help_add(self):
print 'help for add'
def do_EOF(self,x)
sys.exit()
상속관계의 클래스 정보 알아내기
- isinstance() # 객체가 어떤 클래스에 속해 있는지 확인
- issubclass() # 클래스간의 상속 관계 알아보기
- _bases_ # 슈퍼 클래스 목록 얻기
- _class_ # 인스턴스 객체의 목록 얻기
- _dict_ # 클래스와 인스턴스의 이름 공간 얻기
명령어 해석기 실행
- cmdloop() 메쏘드 실행
협동적 클래스와 슈퍼
협동적 클래스?
- 상속 관계에 있는 클래스들이 super 콜을 이용하여 협동적으로 하나의 작업을 수행하는 것
-super(자신의 클래스이름,self).메쏘드()
-MRO(method resolution order)에 따라서 수펴 클래스의 메쏘드를 자동으로 호출한다 # 다이아몬드형 다중 상속시 유용
# 부모 클래스의 이름을 정확히 몰라도 사용 가능
- 슈퍼 클래스는 반드시 Object로부터 상속 받아야 한다
내장 자료형과 클래스 # 2.2부터
- 자료형과 생성자 이름 일치
type('')(123) == str(123)
- 클래스와 자료형의 일치
내장 자료형 서브 클래싱하기(Stack)
class Stack(list):
push = list.append
s = Stack()
s.push(1)
s.pust('spam')
s # [1,'spam']
내장 자료형 서브 클래싱(XML 형식 출력하기)
class xmldic(dict):
def _repr_(self):
res = ['\n<dictionary>']
for k,v in self.items():
res.append('<member>')
res.append('<name>%s</name>
다형성(Polymorphism)
- "여러 개의 형태를 가진다"
- 상속 관계에 있는 다른 클래스들의 인스턴스들이 같은 멤버 함수 호출에 대해 각각 다르게 반응하는 것
- 오버로딩? # 다양한 인수에 적용되는 함수.. 인수에 따라 함수 각각 정의
class Animal:
def cry(self):
print '...'
class Dog(Animal):
def cry(self):
print '멍멍'
class Duck(Anmail):
def cry(self):
print '꽥꽥'
for each in (Dog(), Duck(), Fish()):
each.cry()
상속. 합성.
is-a has-a
캡슐화(encapsulation)
- 필요한 메쏘드와 멤버를 하나의 단위로 묶어 외부에서 접근 가능하도록 인터페이스를 제공 하는 것
캡슐화 방식
- 비공개 방식(black box)
- 공개 방식(white box)
정보 은닉(information hidiong)
- 정보를 숨기는 것
Private 이름 변경 기능
_ _로 시작하는 이름을 정의. 앞에 _클래스 이름이 추가된다.
Encapsulation _x -> _Encapsulation _x
위임(Delegation)이란?
- 상속 메카니즘 대신에 사용되는 기법
- 자신이 처리할 수 없는 메시지(메쏘드 호출)을 수신하면, 그 메시지를 처리할 수 있는 다른 객체로 전달하는 것
- _getattr_을 이용 # 정의되지 않는 속성을 참조할 때 호출된다
_getattr(self,name)
문서 문자열
- 클래스나 메쏘드 몸체에 처음으로 오는 문자열은 문서 문자열로 간주된다.
#_doc_, 도움말 등으로도 쓸 수 있다