버전 |
메소드(Method) |
연산자(Operator) |
인스턴스 o에 대한 사용 예 |
Python2.x/3.x |
__add__(self, B) |
+ (이항) |
o + B, o += B |
Python2.x/3.x |
__sub__(self, B) |
- (이항) |
o - B, o -= B |
Python2.x/3.x |
__mul__(self, B) |
* |
o * B, o *= B |
Python2.x |
__div__(self, B) |
/ |
o / B, o /= B |
Python3.x |
__truediv__(self, B) |
/ |
o / B, o /= B |
Python2.x |
__rdiv__(self, B) |
/ |
B / o |
Python3.x |
__rtruediv__(self, B) |
/ |
B / o |
Python2.x/3.x |
__floordiv__(self, B) |
// |
o // B, o //= B |
Python2.x/3.x |
__mod__(self, B) |
% |
o % B, o %= B |
Python2.x/3.x |
__divmod__(self, B) |
divmod() |
divmod(o, B) |
Python2.x/3.x |
__pow__(self, B) |
pow(), ** |
pow(o, B), o ** B |
Python2.x/3.x |
__lshift__(self, B) |
<< |
o << B, o <<= B |
Python2.x/3.x |
__rshift__(self, B) |
>> |
o >> B, o >>= B |
Python2.x/3.x |
__and__(self, B) |
& |
o & B, o &= B |
Python2.x/3.x |
__xor__(self, B) |
^ |
o ^ B, o ^= B |
Python2.x/3.x |
__or__(self, B) |
| |
o | B, o |= B |
Python2.x/3.x |
__neg__(self) |
- (단항) |
-A |
Python2.x/3.x |
__abs__(self) |
abs() |
abs(o) |
Python2.x/3.x |
__pos__(self) |
+ (단항) |
+o |
Python2.x/3.x |
__invert__(self) |
~ |
~o |
class MyInteger:
def __init__(self, i):
self.i = i
def __str__(self):
return str(self.i)
def __add__(self, other):
return self.i + other
def __sub__(self, other):
return self.i - other
def __mul__(self, other):
return self.i * other
i = MyInteger(10)
print(i)
print(str(i))
print()
i = i + 10
print(i)
print(type(i))
print()
i += 10
print(i)
print()
i += 15
print(i)
print()
i *= 10
print(i)
10 10 20 <class 'int'> 30 45 450
class MyInteger2:
def __init__(self, i):
self.i = i
def __str__(self):
return str(self.i)
def __add__(self, other):
return MyInteger2(self.i + other)
def __sub__(self, other):
return MyInteger2(self.i - other)
def __mul__(self, other):
return MyInteger2(self.i * other)
i = MyInteger2(10)
print(i)
print(str(i))
print()
i = i + 10
print(i)
print(type(i))
print()
i += 10
print(i)
print()
i += 15
print(i)
print()
i *= 10
print(i)
10 10 20 <class '__main__.MyInteger2'> 30 45 450
#python3.x
class MyString:
def __init__(self, str):
self.str = str
def __truediv__(self, sep): # 나누기 연산자 /가 사용되었을 때 호출되는 함수
return self.str.split(sep) # 문자열 self.str을 sep를 기준으로 분리
m = MyString("abcd_abcd_abcd")
print(m / "_")
print(m / "_a")
print()
print(m.__truediv__("_"))
['abcd', 'abcd', 'abcd'] ['abcd', 'bcd', 'bcd'] ['abcd', 'abcd', 'abcd']
#python2.x
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__("_"))
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-9-2a6516d1395e> in <module> 8 9 m = MyString("abcd_abcd_abcd") ---> 10 print(m / 1) 11 print(m / "_a") 12 TypeError: unsupported operand type(s) for /: 'MyString' and 'int'
#python3.x
class MyString:
def __init__(self, str):
self.str = str
def __truediv__(self, sep):
return str.split(self.str, sep)
__rtruediv__ = __truediv__
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 __neg__(self):
t = list(self.str)
t.reverse()
return ''.join(t)
__invert__ = __neg__
m = MyString("abcdef")
print(-m)
print(~m)
fedcba fedcba
class MyString:
def __init__(self, str):
self.str = str
def __neg__(self):
t = list(self.str)
t.reverse()
return MyString(''.join(t))
def __str__(self):
return self.str
__invert__ = __neg__
m = MyString("abcdef")
m = -m
print(m)
m = ~m
print(m)
fedcba abcdef
class MyString:
def __init__(self, str):
self.str = str
def __floordiv__(self, sep):
return self.str.split(sep)[0]
def __mod__(self, sep):
return self.str.split(sep)[1]
def __divmod__(self, sep):
seperated_list = self.str.split(sep)
return seperated_list[0], seperated_list[-1]
m = MyString("aaaa_bbbb_cccc")
print(m // "_")
print(m % "_")
print(divmod(m, "_"))
print()
print(m.__floordiv__("_"))
print(m.__mod__("_"))
print(m.__divmod__("_"))
aaaa bbbb ('aaaa', 'cccc') aaaa bbbb ('aaaa', 'cccc')
메소드 | 연산자 | 비고 |
---|---|---|
__cmp__(self, other) | 아래 메소드가 부재한 상황에 호출되는 메소드 | python3.x 에서는 지원하지 않음 |
__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 |
#python3.x
class MyInteger:
def __init__(self, i):
self.i = i
def __gt__(self, y):
return self.i > y
def __ge__(self, y):
return self.i >= y
def __lt__(self, y):
return self.i < y
def __le__(self, y):
return self.i <= y
def __eq__(self, y):
return self.i == y
def __ne__(self, y):
return self.i != y
c = MyInteger(10)
print(c > 1)
print(c >= 1)
print(c < 1)
print(c <= 1)
print()
print(c == 1)
print(c != 1)
True True False False False True
#python3.x
class MyInteger:
def __init__(self, i):
self.i = i
def __gt__(self, y):
if isinstance(y, MyInteger):
return self.i > y.i
elif isinstance(y, int):
return self.i > y
else:
return False
def __ge__(self, y):
if isinstance(y, MyInteger):
return self.i >= y.i
elif isinstance(y, int):
return self.i >= y
else:
return False
def __lt__(self, y):
if isinstance(y, MyInteger):
return self.i < y.i
elif isinstance(y, int):
return self.i < y
else:
return False
def __le__(self, y):
if isinstance(y, MyInteger):
return self.i <= y.i
elif isinstance(y, int):
return self.i <= y
else:
return False
def __eq__(self, y):
if isinstance(y, MyInteger):
return self.i == y.i
elif isinstance(y, int):
return self.i == y
else:
return False
def __ne__(self, y):
if isinstance(y, MyInteger):
return self.i != y.i
elif isinstance(y, int):
return self.i != y
else:
return False
c = MyInteger(10)
d = MyInteger(100)
e = 50
print(c > d)
print(c >= d)
print()
print(c > e)
print(c >= e)
print()
print(c < d)
print(c <= d)
print()
print(c < e)
print(c <= e)
print()
print(c == d)
print(c != d)
print()
print(c == e)
print(c != e)
False False False False True True True True False True False True
메소드 | 연산자 |
---|---|
__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) |
#python3.x
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("Out of Index - " + str(k))
return k * k
s1 = Square(10)
print(len(s1)) # s1.__len__()
print()
print(s1[0]) #s1.__getitem__(0)
print(s1[1]) #s1.__getitem__(1)
print(s1[4]) #s1.__getitem__(4)
print(s1[9]) #s1.__getitem__(9)
print(s1[20])
10 0 1 16 81
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-4-40a212cf3605> in <module> 19 print(s1[4]) #s1.__getitem__(4) 20 print(s1[9]) #s1.__getitem__(9) ---> 21 print(s1[20]) <ipython-input-4-40a212cf3605> in __getitem__(self, k) 9 def __getitem__(self, k): 10 if k < 0 or self.end <= k: ---> 11 raise IndexError("Out of Index - " + str(k)) 12 return k * k 13 IndexError: Out of Index - 20
s1 = Square(10)
for x in s1:
print(x, end=" ")
0 1 4 9 16 25 36 49 64 81
s2 = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
for x in s2:
#print(x,)
print(x, end=" ")
0 1 4 9 16 25 36 49 64 81
print(list(s1))
print(tuple(s1))
print(type(s1))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] (0, 1, 4, 9, 16, 25, 36, 49, 64, 81) <class '__main__.Square'>
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 object at 0x10d6553c8> 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 list(self.d.keys())
def values(self):
return list(self.d.values())
def items(self):
return list(self.d.items())
m = MyDict({'one':1, 'two':2, 'three':3})
print(m.keys())
print(m.values())
print(m.items())
['one', 'two', 'three'] [1, 2, 3] [('one', 1), ('two', 2), ('three', 3)]
class StringRepr:
def __repr__(self):
return 'repr called'
def __str__(self):
return 'str called'
s = StringRepr()
print(s)
print(str(s))
print(repr(s))
str called str called repr called
class StringRepr:
def __repr__(self):
return 'repr called'
s = StringRepr()
print(s)
print(str(s))
print(repr(s))
repr called repr called repr called
class StringRepr:
def __str__(self):
return 'str called'
s = StringRepr()
print(s)
print(str(s))
print(repr(s))
str called str called <__main__.StringRepr object at 0x10d658470>
eval('10 + 20')
30
a = '10 + 20'
eval(a)
30
b = "print('abc')"
eval(b)
abc
class StringRepr:
def __init__(self, i = 10):
self.i = i
def __repr__(self):
return 'StringRepr(100)'
s = StringRepr()
q = eval(repr(s))
print(q.i)
100
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
def check(func):
if callable(func):
print('callable')
else:
print('not callable')
a = A()
b = B()
check(a)
check(b)
print()
print(callable(a))
print(callable(b))
callable not callable True False
참고 문헌: 파이썬(열혈강의)(개정판 VER.2), 이강성, FreeLec, 2005년 8월 29일