class Person:
def __init__(self, name, phone=None):
self.name = name
self.phone = phone
def __str__(self):
return '<Person %s %s>' % (self.name, self.phone)
class Employee(Person): # 괄호 안에 쓰여진 클래스는 슈퍼클래스를 의미한다.
def __init__(self, name, phone, position, salary):
Person.__init__(self, name, phone) # Person클래스의 생성자 호출
self.position = position
self.salary = salary
p1 = Person('홍길동', 1498)
print p1.name
print p1
print
m1 = Employee('손창희', 5564, '대리', 200)
m2 = Employee('김기동', 8546, '과장', 300)
print m1.name, m1.position # 슈퍼클래스와 서브클래스의 멤버를 하나씩 출력한다.
print m1
print m2.name, m2.position
print m2
홍길동 <Person 홍길동 1498> 손창희 대리 <Person 손창희 5564> 김기동 과장 <Person 김기동 8546>
class Super:
def __init__(self):
print 'Super init called'
class Sub(Super):
def __init__(self):
print 'Sub init called'
s = Sub()
Sub init called
class Super:
def __init__(self):
print 'Super init called'
class Sub(Super):
def __init__(self):
Super.__init__(self) # 명시적으로 슈퍼클래스의 생성자를 호출한다.
print 'Sub init called'
s = Sub()
Super init called Sub init called
class Super:
def __init__(self):
print 'Super init called'
class Sub(Super):
pass
s = Sub()
Super init called
class Person:
def __init__(self, name, phone=None):
self.name = name
self.phone = phone
def __str__(self):
return '<Person %s %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
p1 = Person('gslee', 5284)
m1 = Employee('kslee', 5224, 'President', 500)
print p1
print m1
<Person gslee 5284> <Person kslee 5224>
class Employee(Person):
def __init__(self, name, phone, position, salary):
Person.__init__(self, name, phone)
self.position = position
self.salary = salary
def __str__(self):
return '<Employee %s %s %s %s>' % (self.name, self.phone, self.position, self.salary)
p1 = Person('gslee', 5284)
m1 = Employee('kslee', 5224, 'President', 500)
print p1
print m1
<Person gslee 5284> <Employee kslee 5224 President 500>
상속 관계 내의 다른 클래스들의 인스턴스들이 같은 멤버 함수 호출에 대해 각각 다르게 반응하도록 하는 기능
다형성의 장점
파이썬에서 다형성의 장점
class Animal:
def cry(self):
print '...'
class Dog(Animal):
def cry(self):
print '멍멍'
class Duck(Animal):
def cry(self):
print '꽥꽥'
class Fish(Animal):
pass
for each in (Dog(), Duck(), Fish()):
each.cry()
멍멍 꽥꽥 ...
a = list()
print a
print dir(a)
[] ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
class MyList(list):
def __sub__(self, other): # '-' 연산자 중복 함수 정의
for x in other:
if x in self:
self.remove(x) # 각 항목을 하나씩 삭제한다.
return self
L = MyList([1, 2, 3, 'spam', 4, 5])
print L
print
L = L - ['spam', 4]
print L
[1, 2, 3, 'spam', 4, 5] [1, 2, 3, 5]
class Stack(list): # 클래스 정의
push = list.append
s = Stack() # 인스턴스 생성
s.push(4)
s.push(5)
print s
print
s = Stack([1,2,3])
s.push(4)
s.push(5)
print s
print
print s.pop() # 슈퍼 클래스인 리스트 클래스의 pop() 메소드 호출
print s.pop()
print s
[4, 5] [1, 2, 3, 4, 5] 5 4 [1, 2, 3]
class Queue(list):
enqueue = list.append
def dequeue(self):
return self.pop(0)
q = Queue()
q.enqueue(1) # 데이터 추가
q.enqueue(2)
print q
print q.dequeue() # 데이터 꺼내기
print q.dequeue()
[1, 2] 1 2
a = dict()
print a
print dir(a)
{} ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
class MyDict(dict):
def keys(self):
K = dict.keys(self) # 언바운드 메소드 호출 --> K = self.keys() 라고 호출하면 무한 재귀 호출
K.sort()
return K
d = MyDict({'one':1, 'two':2, 'three':3})
print d.keys()
print
d2 = {'one':1, 'two':2, 'three':3}
print d2.keys()
['one', 'three', 'two'] ['three', 'two', 'one']
import types
print type(123) == types.IntType
print type(123) == type(0)
True True
print isinstance(123, int)
print int
True <type 'int'>
class A:
pass
class B:
def f(self):
pass
class C(B):
pass
def check(obj):
print obj, '=>',
if isinstance(obj, A):
print 'A',
if isinstance(obj, B):
print 'B',
if isinstance(obj, C):
print 'C',
print
a = A()
b = B()
c = C()
check(a)
check(b)
check(c)
<__main__.A instance at 0x10de34e60> => A <__main__.B instance at 0x10de34e18> => B <__main__.C instance at 0x10de34cf8> => B C
class A:
pass
class B:
def f(self):
pass
class C(B):
pass
def check(obj):
print obj, '=>',
if issubclass(obj, A):
print 'A',
if issubclass(obj, B):
print 'B',
if issubclass(obj, C):
print 'C',
print
check(A)
check(B)
check(C)
__main__.A => A __main__.B => B __main__.C => B C
참고 문헌: 파이썬(열혈강의)(개정판 VER.2), 이강성, FreeLec, 2005년 8월 29일