class S1:
a = 1
print S1.a
print
S1.b = 2 # 클래스 이름 공간에 새로운 이름의 생성
print S1.b
print
print dir(S1) # S1에 포함된 이름들을 리스트로 반환
del S1.b # 이름 공간 S1에서 b삭제
print dir(S1)
1 2 ['__doc__', '__module__', 'a', 'b'] ['__doc__', '__module__', 'a']
x = S1() # x는 S1의 클래스 인스턴스
print x.a
x.a = 10 # 클래스 인스턴스 x의 이름 공간에 이름 생성
print x.a
print S1.a # 클래스 이름 공간과 클래스 인스턴스의 이름공간은 다르다
1 10 1
y = S1() # S1 클래스의 또 다른 인스턴스 생성
y.a = 300 # 클래스 인스턴스 y의 이름 공간에 이름 생성
print y.a
print x.a # x 인스턴스 공간의 이름 a 확인
print S1.a # 클래스 이름 공간의 a 확인
300 10 1
class Parent:
a = 10
def f(self):
print 'base'
class Child(Base): # 클래스 Parent의 속성을 모두 상속받는다.
b = 100
pass
d = Child()
d.f() # Parent 클래스의 메소드 f가 호출된다.
print d.a
print d.b
base 10 100
class MyClass:
pass
a = MyClass()
print a + 3
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-11-9671fd5ec4de> in <module>() 3 4 a = MyClass() ----> 5 print a + 3 TypeError: unsupported operand type(s) for +: 'instance' and 'int'
class MyClass:
def __add__(self, x): # 이름 __add__는 + 연산자를 Overloading한다.
print 'add %s called' %x
return x
a = MyClass()
print a + 3 # 더하기 연산자가 적용되어 호출됨
add 3 called 3
class Simple:
pass
s1 = Simple()
s2 = Simple()
s1.stack = [] # 동적으로 클래스 인스턴스 이름 공간 안에 새로운 변수(이름) stack 생성
s1.stack.append(1) # 값 추가
s1.stack.append(2)
s1.stack.append(3)
print s1.stack #출력
print s1.stack.pop() #pop
print s1.stack.pop()
print
print s1.stack #최종 s1.stack값
print s2.stack #s2에는 stack 을 정의한 적이 없다.
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-1-fe9f51bee14e> in <module>() ----> 1 s1.stack = [] # 동적으로 클래스 인스턴스 이름 공간 안에 새로운 변수(이름) stack 생성 2 s1.stack.append(1) # 값 추가 3 s1.stack.append(2) 4 s1.stack.append(3) 5 NameError: name 's1' is not defined
del s1.stack # s1에서 stack삭제
#class01.py
class MyClass:
def set(self, v):
self.value = v
def get(self):
return self.value
c = MyClass() # 인스턴스 생성
c.set('egg') # 메소드 set 호출
print c.get() # 메소드 put 호출
print c.value # 인스턴스 변수에 직접 접근
egg egg
c = MyClass() # 인스턴스 생성
MyClass.set(c, 'egg')
print MyClass.get(c)
print c.value
egg egg
class Simple:
pass
c = MyClass()
s1 = Simple()
MyClass.set(s1, 'egg') # 다른 클래스의 인스턴스를 넣어주면 에러 발생
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-14-0660940f4507> in <module>() 4 c = MyClass() 5 s1 = Simple() ----> 6 MyClass.set(s1, 'egg') # 다른 클래스의 인스턴스를 넣어주면 에러 발생 TypeError: unbound method set() must be called with MyClass instance as first argument (got Simple instance instead)
class MyClass:
def set(self, v):
self.value = v
def incr(self):
self.set(self.value + 1) # 내부 메소드 호출
def get(self):
return self.value
c = MyClass()
c.set(1)
print c.get()
print
c.incr()
print c.get()
1 2
def set(i):
print "set function outside function - ", i
class MyClass:
def set(self, v):
self.value = v
def incr(self):
set(self.value + 1) # 정적 영역에 존재하는 set 메소드 호출
def get(self):
return self.value
c = MyClass()
c.set(1)
print c.get()
print
c.incr()
print c.get()
1 set function outside function - 2 1
class D:
def spam(x, y): # self가 없다.
print 'static method', x, y
spam = staticmethod(spam) # static method로 등록, 좌변의 이름이 정적 메소드의 이름이다.
D.spam(1,2) # 인스턴스 객체 없이 클래스에서 직접 호출
print
d = D()
d.spam(1,2) # 인스턴스 객체를 통해서도 호출 가능
static method 1 2 static method 1 2
class D:
@staticmethod
def spam(x, y): # self가 없다.
print 'static method', x, y
D.spam(1,2) # 인스턴스 객체 없이 클래스에서 직접 호출
print
d = D()
d.spam(1,2) # 인스턴스 객체를 통해서도 호출 가능
static method 1 2 static method 1 2
class C:
def spam(cls, y):
print cls, '->', y
spam = classmethod(spam)
print C
print
C.spam(5) # 첫번째 인수로 C가 잠재적으로 전달된다.
print
c = C()
c.spam(5)
__main__.C __main__.C -> 5 __main__.C -> 5
class C:
@classmethod
def spam(cls, y):
print cls, '->', y
print C
print
C.spam(5) # 첫번째 인수로 C가 잠재적으로 전달된다.
print
c = C()
c.spam(5)
__main__.C __main__.C -> 5 __main__.C -> 5
class D(C):
pass
print D.spam(3)
d = D()
print d.spam(3)
__main__.D -> 3 None __main__.D -> 3 None
def f1(f):
print 'in f1', f
return f
def f2(f):
print 'in f2', f
return f
def f3(f):
print 'in f3', f
return f
@f1
@f2
@f3
def f():
return f
in f3 <function f at 0x10ded55f0> in f2 <function f at 0x10ded55f0> in f1 <function f at 0x10ded55f0>
def f1(f):
print 'in f1', f
return f
def f2(f):
print 'in f2', f
return f
def f3(f):
print 'in f3', f
return f
def g():
return g
f1(f2(f3(g)))
in f3 <function g at 0x10ded5de8> in f2 <function g at 0x10ded5de8> in f1 <function g at 0x10ded5de8>
<function __main__.g>
class Var:
c_mem = 100 # 클래스 멤버 정의
def f(self):
self.i_mem = 200 # 인스턴스 멤버 정의
def g(self):
print self.i_mem
print self.c_mem
print Var.c_mem # 클래스 객체를 통하여 클래스 멤버 접근
v1 = Var() # 인스턴스 v1 생성
v1.f() # 인스턴스 멤버 i_mem이 생성됨
print v1.i_mem # 인스턴스 v1을 통하여 인스턴스 멤버 접근
print
v2 = Var() # 인스턴스 v2 생성
print v2.i_mem # 인스턴스 v2에는 아직 f() 호출이 안되어서 i_mem 멤버 없음 ==> 생성자의 필요성
100 200
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-5-1a1c5a7fa01d> in <module>() 7 print 8 v2 = Var() # 인스턴스 v2 생성 ----> 9 print v2.i_mem # 인스턴스 v2에는 아직 f() 호출이 안되어서 i_mem 멤버 없음 ==> 생성자의 필요성 AttributeError: Var instance has no attribute 'i_mem'
print v1.c_mem # 인스턴스 v1을 통해 클래스 멤버 참조
print v2.c_mem # 인스턴스 v2를 통해 클래스 멤버 참조
print
v1.c_mem = 50 # 인스턴스 이름 공간에 c_mem생성
print v1.c_mem # 인스턴스 v1을 통해 인스턴스 멤버 참조
print v2.c_mem # 인스턴스 v2을 통해 클래스 멤버참조 (인스턴스 멤버가 없으므로, 클래스 멤버 참조)
print Var.c_mem # 클래스 멤버참조
100 100 50 100 100
class Const:
def initialize(self):
self.hand = 2
self.foot = 2
self.eye = 2
def print_info(self):
print 'hands=%s foot=%s eyes=%s' % (self.hand, self.foot, self.eye)
c = Const()
c.initialize()
c.print_info()
hands=2 foot=2 eyes=2
# _*_ coding:utf-8 _*_
from time import ctime, sleep
class Life:
def __init__(self): # 생성자
self.birth = ctime() # 현재시간에 대한 문자열을 얻는다.
print 'Birthday', self.birth # 현재 시간 출력
def __del__(self): # 소멸자
print 'Deathday', ctime() # 소멸 시간 출력
def test():
mylife = Life()
print 'Sleeping for 3 sec'
sleep(3) #3초간 sleep(block)상태에 있음 (CPU 점유 못함)
test()
Birthday Thu Nov 6 21:51:25 2014 Sleeping for 3 sec Deathday Thu Nov 6 21:51:28 2014
class Integer:
def __init__(self, i):
self.i = i
def __str__(self):
return str(self.i)
i = Integer(10)
print i
print str(i)
10 10
메소드(Method) |
연산자(Operator) |
인스턴스 o에 대한 사용 예 |
\_\_add\_\_(self, B) |
+ (이항) |
o + B, o += B |
\_\_sub\_\_(self, B) |
- (이항) |
o - B, o -= B |
\_\_mul\_\_(self, B) |
\* |
o \* B, o \*= B |
\_\_div\_\_(self, B) |
/ |
o / B, o /= B |
\_\_floordiv\_\_(self, B) |
// |
o // B, o //= B |
\_\_mod\_\_(self, B) |
% |
o % B, o %= B |
\_\_divmod\_\_(self, B) |
divmod() |
divmod(o, B) |
\_\_pow\_\_(self, B) |
pow(), \*\* |
pow(o, B), o \*\* B |
\_\_lshift\_\_(self, B) |
<< |
o << B, o <<= B |
\_\_rshift\_\_(self, B) |
>> |
o >> B, o >>= B |
\_\_and\_\_(self, B) |
& |
o & B, o &= B |
\_\_xor\_\_(self, B) |
^ |
o ^ B, o ^= B |
\_\_or\_\_(self, B) |
| |
o | B, o |= B |
\_\_neg\_\_(self) |
- (단항) |
-A |
\_\_abs\_\_(self) |
abs() |
abs(o) |
\_\_pos\_\_(self) |
+ (단항) |
+o |
\_\_invert\_\_(self) |
~ |
~o |
class Integer:
def __init__(self, i):
self.i = i
def __str__(self):
return str(self.i)
def __add__(self, other):
return self.i + other
i = Integer(10)
print i
print str(i)
print
i = i + 10
print i
print
i += 10
print i
10 10 20 30
class MyString:
def __init__(self, str):
self.str = str
def __div__(self, sep): # 나누기 연산자 /가 사용되었을 때 호출되는 함수
return self.str.split(sep) # 문자열 self.str을 sep를 기준으로 분리
m = MyString("abcd_abcd_abcd")
print m / "_"
print m / "_a"
print
print m.__div__("_")
['abcd', 'abcd', 'abcd'] ['abcd', 'bcd', 'bcd'] ['abcd', 'abcd', 'abcd']
class MyString:
def __init__(self, str):
self.str = str
def __div__(self, sep):
return str.split(self.str, sep)
__rdiv__ = __div__
m = MyString("abcd_abcd_abcd")
print m / "_"
print m / "_a"
print
print "_" / m
print "_a" / m
['abcd', 'abcd', 'abcd'] ['abcd', 'bcd', 'bcd'] ['abcd', 'abcd', 'abcd'] ['abcd', 'bcd', 'bcd']
class MyString:
def __init__(self, str):
self.str = str
def __div__(self, sep):
return str.split(self.str, sep)
__rdiv__ = __div__
def __neg__(self):
t = list(self.str)
t.reverse()
return ''.join(t)
__invert__ = __neg__
m = MyString("abcdef")
print -m
print ~m
fedcba fedcba
class MyNum:
def __init__(self, n):
self.n = n
def __coerce__(self, y):
return self.n, y # (숫자, 숫자)의 리턴
a = MyNum(10)
print a + 20
print a * 30
print a / 2
print a % 2
print divmod(a, 3)
30 300 5 0 (3, 1)
class MyNum:
def __init__(self, n):
self.n = n
def __coerce__(self, y):
return self, y # (객체, 숫자)의 리턴
def __add__(self, y):
print 'add called'
return self.n + y
x = MyNum(12)
print x + 4
add called 16
메소드 | 연산자 |
---|---|
__len__(self) | len() |
__contains__(self, item) | item in self |
__getItem__(self, key) | self[key] |
__setItem__(self, key, value) | self[key] = value |
__delItem__(self, key) | del self(key) |
class Square:
def __init__(self, end):
self.end = end
def __len__(self):
return self.end
def __getitem__(self, k):
if k < 0 or self.end <= k:
raise IndexError, k
return k * k
s1 = Square(10)
print len(s1) # s1.__len__()
print s1[1] # s1.__getitem__(1)
print s1[4]
print s1[20]
10 1 16
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-3-78c6c0117c4f> in <module>() 13 print s1[1] #s1.__getitem__(1) 14 print s1[4] ---> 15 print s1[20] <ipython-input-3-78c6c0117c4f> in __getitem__(self, k) 6 def __getitem__(self, k): 7 if k < 0 or self.end <= k: ----> 8 raise IndexError, k 9 return k * k 10 IndexError: 20
for x in s1:
print x,
0 1 4 9 16 25 36 49 64 81
print list(s1)
print tuple(s1)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] (0, 1, 4, 9, 16, 25, 36, 49, 64, 81)
s = slice(1, 10, 2)
print s
print type(s) # s의 형(Type) 정보를 알아본다
print dir(s) # s의 속성 리스트를 보여준다.
slice(1, 10, 2) <type 'slice'> ['__class__', '__cmp__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'indices', 'start', 'step', 'stop']
print slice(10)
print slice(1, 10)
print slice(1, 10, 3)
slice(None, 10, None) slice(1, 10, None) slice(1, 10, 3)
import types
class Square:
def __init__(self, end):
self.end = end
def __len__(self):
return self.end
def __getitem__(self, k):
if type(k) == types.IntType: # indexing
if k < 0 or self.end <= k:
raise IndexError, k
return k * k
elif type(k) == types.SliceType: # Slicing
start = k.start or 0
if k.stop > self.end:
stop = self.end
else:
stop = k.stop
step = k.step or 1
return map(self.__getitem__, range(start, stop, step))
s = Square(10)
print s[4] # 인덱싱
print s[1:5] # 슬라이싱
print s[1:10:2] # 간격은 2로
print s[:] # 전체범위
16 [1, 4, 9, 16] [1, 9, 25, 49, 81] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
class MyDict:
def __init__(self, d = None):
if d == None:
d = {}
self.d = d
def __getitem__(self, k): # key
return self.d[k]
def __setitem__(self, k, v):
self.d[k] = v
def __len__(self):
return len(self.d)
m = MyDict() #__init__호출
m['day'] = 'light' #__setitem__호출
m['night'] = 'darkness' #__setitem__호출
print m
print m['day'] #__getitem__호출
print m['night'] #__getitem__호출
print len(m) #__len__호출
<__main__.MyDict instance at 0x10de1b710> light darkness 2
class MyDict:
def __init__(self, d=None):
if d == None: d = {}
self.d = d
def __getitem__(self, k):
return self.d[k]
def __setitem__(self, k, v):
self.d[k] = v
def __len__(self):
return len(self.d)
def keys(self):
return self.d.keys()
def values(self):
return self.d.values()
def items(self):
return self.d.items()
m = MyDict({'one':1, 'two':2, 'three':3})
print m.keys()
print m.values()
print m.items()
['three', 'two', 'one'] [3, 2, 1] [('three', 3), ('two', 2), ('one', 1)]
class StringRepr:
def __repr__(self):
return 'repr called'
def __str__(self):
return 'str called'
s = StringRepr()
print s
print str(s)
print repr(s)
print `s`
str called str called repr called repr called
print repr(1) # 숫자 1에 대한 repr 문자열 표현
print repr('abc') # 문자열 'abc'에 대한 repr문자열 표현
print repr([1,2,3]) # 리스트 [1,2,3]에 대한 repr 문자열 표현
print
a = eval('1') # <--숫자
b = eval("'abc'") # <--문자열
c = eval('[1,2,3]') # <--리스트
print type(a), type(b), type(c)
1 'abc' [1, 2, 3] <type 'int'> <type 'str'> <type 'list'>
class StringRepr:
def __repr__(self):
return 'repr called'
s = StringRepr()
print s
print repr(s)
print str(s)
print `s`
repr called repr called repr called repr called
class StringRepr:
def __str__(self):
return 'str called'
s = StringRepr()
print s
print repr(s)
print str(s)
print `s`
str called <__main__.StringRepr instance at 0x101d3f908> str called <__main__.StringRepr instance at 0x101d3f908>
메소드 | 연산자 | 비고 |
---|---|---|
__cmp__(self, other) | self < other 인 경우 음의 정수, self == other 인 경우 0, self > other 인 경우 양의 정수를 리턴해야 함 | 아래 메소드가 부재한 상황에 호출되는 메소드 |
__lt__(self, other) | self < other | |
__le__(self, other) | self <= other | |
__eq__(self, other) | self == other | |
__ne__(self, other) | self != other | |
__gt__(self, other) | self > other | |
__ge__(self, other) | self >= other |
class MyCmp:
def __init__(self, value):
self.value = value
def __cmp__(self, other):
return self.value - other
c = MyCmp(10)
print c > 1 # c.__cmp__(1)을 호출, 반환값이 양수이면 True
print c < 1 # c.__cmp__(1)을 호출, 반환값이 음수이면 True
print c == 1 # c.__cmp__(1)을 호출, 반환값이 0이면 True
True False False
class MyCmp2:
def __init__(self, value):
self.value = value
def __lt__(self, other):
return self.value < other
m = MyCmp2(5)
print m < 10 # m.__lt__(10)을 호출
print m < 2
print m < 1
True False False
print bool(12), bool(0)
print bool(1.4), bool(0.0)
print bool([]), bool(()), bool({})
True False True False False False False
class Truth:
def __init__(self, num):
self.num = num
def __nonzero__(self):
return self.num == 10 #num이 10일 경우만 참(1)을 리턴
t = Truth(3) # num에 3 설정
print bool(t)
t.num = 10 # num에 10 설정
print bool(t)
False True
class Truth:
def __init__(self, num):
self.num = num
def __len__(self):
return self.num
t = Truth(3) # num에 3 설정
print bool(t)
t.num = 0 # num에 0 설정
print bool(t)
True False
class AlwaysTrue:
pass
t = AlwaysTrue()
print bool(t)
True
class Accumulator:
def __init__(self):
self.sum = 0
def __call__(self, *args):
self.sum += sum(args)
return self.sum
acc = Accumulator()
print acc(1,2,3,4,5)
print acc(6)
print acc(7,8,9)
print acc.sum
15 21 45 45
class A:
def __call__(self, v):
return v
class B:
def func(self, v):
return v
a = A()
b = B()
print callable(a)
print callable(b)
True False
import string
class F:
pass
def f():
pass
print callable(string)
print callable(F)
print callable(f)
False True True
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)
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.display()
print
m1 = Employee('손창희', 5564, '대리', 200)
m2 = Employee('김기동', 8546, '과장', 300)
print m1.name, m1.position # 슈퍼클래스와 서브클래스의 멤버를 하나씩 출력한다.
print m1.display()
print m2.name, m2.position
print m2.display()
홍길동 <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 __repr__(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 __repr__(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 Person:
def __init__(self, name, phone=None):
self.name = name
self.phone = phone
def __repr__(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
def __repr__(self):
s = Person.__repr__(self)
return s + ' <Employee %s %s>' % (self.position, self.salary)
p1 = Person('gslee', 5284)
m1 = Employee('kslee', 5224, 'President', 500)
print p1
print m1
<Person gslee 5284> <Person kslee 5224> <Employee President 500>
is-a 관계의 예
A is a B
# mymath.py
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def area(self): # 점의 면적은 0
return 0
def move(self, dx, dy):
self.x += dx
self.y += dy
def __repr__(self):
return 'x=%s y=%s' %(self.x, self.y)
class Circle(Point):
def __init__(self, x, y, r):
Point.__init__(self, x, y)
self.radius = r
def area(self): # 원의 면적
return math.pi * self.radius * self.radius
def __repr__(self):
return '%s radius=%s' % (Point.__repr__(self), self.radius)
class Cylinder(Circle):
def __init__(self, x, y, r, h):
Circle.__init__(self, x, y, r)
self.height = h
def area(self): # 위 아래의 원의 면적 + 기둥의 표면적
return 2 * Circle.area(self) + 2 * math.pi * self.radius * self.height
def volume(self): # 체적
return Circle.area(self) * self.height
def __repr__(self):
return '%s height=%s' %(Circle.__repr__(self), self.height)
if __name__ == '__main__':
p1 = Point(3, 5)
c1 = Circle(3, 4, 5)
c2 = Cylinder(3, 4, 5, 6)
print p1
print
print c1
print c1.area()
print
print c2
print c2.area(), c2.volume()
print
p1.move(10, 10)
print p1
x=3 y=5 x=3 y=4 radius=5 78.5398163397 x=3 y=4 radius=5 height=6 345.575191895 471.238898038 x=13 y=15
가상 함수
아래 예제 설명
class Base:
def f(self):
self.g() # 함수 g() 호출
def g(self):
print 'Base'
class Derived(Base):
def g(self): # 파생클래스의 함수 g()
print 'Derived'
b = Base()
b.f()
a = Derived()
a.f()
Base Derived
class Stack(list): # 클래스 정의
def push(self, other):
self.append(other)
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):
def enqueue(self, other):
self.append(other)
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
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
class Simple:
member = 1
def method(self):
self.method2 = 'HERE'
s = Simple()
print s.__class__ # 클래스 객체 얻어내기
print s.__class__.__name__ # 클래스 이름 알아내기
__main__.Simple Simple
class Simple:
memeber = 1
def f(self):
self.value = 'HERE'
print Simple.__dict__ # 클래스 이름공간 확인
print Simple.__dict__.keys() # 클래스 이름공간의 이름만 확인
{'memeber': 1, '__module__': '__main__', '__doc__': None, 'f': <function f at 0x10deb67d0>} ['memeber', '__module__', '__doc__', 'f']
s = Simple()
print s.__dict__ # 처음에는 인스턴스 이름 공간에 아무것도 정의되어 있지 않다.
s.f() # 인스턴스 메소드 f()를 호출하여 인스턴스 객체에 value를 정의한다.
print s.__dict__
s.attr = 'attribute' # 새로운 다른 멤버들을 외부에서 정의
s.num1 = 10
print s.__dict__
{} {'value': 'HERE'} {'attr': 'attribute', 'value': 'HERE', 'num1': 10}
print dir(s)
print s.__dict__.keys()
print
print dir(Simple)
print Simple.__dict__.keys()
['__doc__', '__module__', 'attr', 'f', 'memeber', 'num1', 'value'] ['attr', 'value', 'num1'] ['__doc__', '__module__', 'f', 'memeber'] ['memeber', '__module__', '__doc__', 'f']
class A(object):
def a(self):
pass
class B(A):
def b(self):
pass
class C(B):
def c(self):
pass
c = C()
print dir(c) # 인스턴스 객체의 속성에 클래스 객체의 속성까지도 포함해서 표시
print "-" * 10
print
print dir(C) # 슈퍼클래스의 속성도 함께 표시
print "-" * 10
print
print dir(B)
print "-" * 10
print
print dir(A)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'c'] ---------- ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'c'] ---------- ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b'] ---------- ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a']
class Simple():
pass
s = Simple()
print Simple
print type(s) # s의 자료형은?
print s.__class__ # s의 클래스는?
print
print s.__class__ == type(s) #s의 자료형과 s의 클래스는 같은행인가?
print
print s
__main__.Simple <type 'instance'> __main__.Simple False <__main__.Simple instance at 0x10d8b8440>
class Simple(object):
pass
s = Simple()
print Simple
print type(s) # s의 자료형은?
print s.__class__ # s의 클래스는?
print
print s.__class__ == type(s) #s의 자료형과 s의 클래스는 같은행인가?
print
print s
<class '__main__.Simple'> <class '__main__.Simple'> <class '__main__.Simple'> True <__main__.Simple object at 0x10dee4690>
print dir(object)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
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 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']
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()
멍멍 꽥꽥 ...
다형성의 장점
파이썬에서 다형성의 장점
class IntegerAdder:
def __init__(self, value = 0):
self.value = value
def __add__(self, value):
try:
return IntegerAdder(self.value + int(value))
except:
return self
def __repr__(self):
return `self.value`
a = IntegerAdder(5)
print a + 4 # 정수덧셈
print a + 4.5 # 실수덧셈
print a + '1234' # 정수로 변환 가능한 문자열 덧셈
print a + 'abc' # 정수로 변환 가능하지 않은 문자열 덧셈
9 9 1239 5
#Inheritance
class Set(list): # 변경 가능(Mutable) 집합
def union(self, A):
for x in A:
if x not in self:
self.append(x)
return Set(self)
A = Set([1,2,3])
B = Set([3,4,5])
print A.union(B)
print A
print
class Set2(list): # 변경 불가능(Immutable) 집합
def union(self, A):
res = self[:]
for x in A:
if x not in res:
res.append(x)
return Set(res)
A = Set2([1,2,3])
B = Set2([3,4,5])
print A.union(B)
print A
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3]
#composition
class Set: # list를 상속하지 않음, 변경 불가능(Immutable) 집합
def __init__(self, d = None):
self.data = d
def union(self, A):
res = self.data[:]
for x in A:
if x not in res:
res.append(x)
return Set(res)
def __getitem__(self, k):
return self.data[k]
def __repr__(self):
return `self.data`
A = Set([1,2,3])
B = Set([3,4,5])
print A.union(B)
print A
[1, 2, 3, 4, 5] [1, 2, 3]
상속
합성
캡슐화 (Encapsulation)
캡슐화의 종류
파이썬에서는 모든 속성이 public 이다.
파이썬에서 private 속성/메소드를 지원하는 방법
class Encapsulation: # 두개의 클래스멤버를 가지는 클래스정의
z = 10
__x = 1
def __g():
pass
print Encapsulation.z # z 는 접근가능
print Encapsulation.__x #__x는 접근가능하지않음, 예외발생
10
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-78-5543e80feb1d> in <module>() 6 7 print Encapsulation.z # z 는 접근가능 ----> 8 print Encapsulation.__x #__x는 접근가능하지않음, 예외발생 AttributeError: class Encapsulation has no attribute '__x'
print dir(Encapsulation)
print
print Encapsulation._Encapsulation__x # 변경된 이름으로 접근 가능
['_Encapsulation__g', '_Encapsulation__x', '__doc__', '__module__', 'z'] 1