인프런 파이썬 중급 - 매직 메소드
- 노트필기/파이썬
- 2021. 4. 29.
In [80]:
# Special Method(Magic Method)
# 파이썬의 핵심
# 시퀀스, 반복, 함수, 클래스
In [81]:
print(int)
<class 'int'>
In [82]:
print(float)
<class 'float'>
In [83]:
# 모든 속성 및 메소드 출력
print(dir(int))
print(dir(float))
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__set_format__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']
In [84]:
n = 10
In [85]:
print(type(n))
<class 'int'>
In [86]:
print(n + 100)
110
In [87]:
print(n.__add__(100))
110
In [88]:
print(n.__doc__)
int([x]) -> integer
int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments
are given. If x is a number, return x.__int__(). For floating point
numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base. The literal can be preceded by '+' or '-' and be surrounded
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
In [89]:
print(n.__bool__())
True
In [90]:
print(n.__bool__(),bool(n))
True True
In [91]:
print(n*100, n.__mul__(100))
1000 1000
In [92]:
#클래스 예제1
class Fruit:
def __init__(self, name, price):
self._name = name
self._price = price
def __str__(self):
return 'Fruit Class Info : {}, {}'.format(self._name, self._price)
def __add__(self, x):
print('Called >> __add__')
return self._price + x._price
def __sub__(self, x):
print('Called >> __sub__')
return self._price - x._price
def __le__(self, x):
print('Called >> __le__')
if self._price <= x._price:
return True
else:
return False
def __ge__(self, x):
print('Called >> __ge__')
if self._price >= x._price:
return True
else:
return False
#인스턴스 생성
s1 = Fruit('Orange', 7500)
s2 = Fruit('Banana', 3000)
In [93]:
print(s1._price + s2._price)
10500
In [94]:
print(s1+s2)
Called >> __add__
10500
In [95]:
print(s1 >= s2)
print(s1 <= s2)
print(s1 - s2)
print(s2 - s1)
print(s1)
print(s2)
Called >> __ge__
True
Called >> __le__
False
Called >> __sub__
4500
Called >> __sub__
-4500
Fruit Class Info : Orange, 7500
Fruit Class Info : Banana, 3000
In [96]:
# 클래스 예제
# (5,2)+(4,3) = (9,5)
# (10,3)*5 = (50,15)
# Max((10,0)) = 10
In [97]:
class Vector(object):
def __init__(self, *args):
'''
Create a vector, example : v = Vector(5,10)
'''
if len(args) == 0:
self._x, self._y = 0,0
else:
self._x, self._y = args
def __repr__(self):
'''Return the vector informations'''
return 'Vector(%r, %r)'%(self._x,self._y)
def __add__(self, other):
'''return the vector add'''
return Vector(self._x + other._x, self._y + other._y)
def __mul__(self, y):
return Vector(self._x*y,self._y*y)
def __bool__(self):
return bool(max(self._x,self._y))
In [98]:
v1 = Vector(5,7)
v2 = Vector(23,35)
v3 = Vector()
In [99]:
v3
Out[99]:
Vector(0, 0)
In [100]:
print(Vector.__init__.__doc__)
print(Vector.__repr__.__doc__)
print(Vector.__add__.__doc__)
Create a vector, example : v = Vector(5,10)
Return the vector informations
return the vector add
In [101]:
print(v1, v2, v3)
Vector(5, 7) Vector(23, 35) Vector(0, 0)
In [102]:
print(v1+v2)
print(v1*3)
print(v2*10)
print(bool(v1),bool(v2),bool(v3))
Vector(28, 42)
Vector(15, 21)
Vector(230, 350)
True True False
In [103]:
if bool(v1):
print('ok')
if bool(v3):
print('ok')
ok
In [104]:
# 객체 -> 파이썬의 데이터를 추상화
# 모든 객체
In [105]:
# 일반적인 튜블
pt1 = (1.0, 5.0)
pt2 = (2.5, 1.5)
from math import sqrt
l_leng1 = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)
print(l_leng1)
3.8078865529319543
In [106]:
# 네임드 튜플 사용
from collections import namedtuple
# 네임드 튜플 선언
Point = namedtuple('Point','x y')
In [107]:
pt3 = Point(1.0, 5.0)
pt4 = Point(2.5, 1.5)
In [108]:
print(pt3)
print(pt4)
Point(x=1.0, y=5.0)
Point(x=2.5, y=1.5)
In [109]:
print(pt3[0])
print(pt3[1])
1.0
5.0
In [110]:
l_leng2 = sqrt((pt3.x-pt4.x)**2 + (pt3.y-pt4.y)**2)
In [111]:
l_leng2
Out[111]:
3.8078865529319543
In [112]:
# 네임드 튜플 선언 방법
Point1 = namedtuple('Point', ['x', 'y'])
Point2 = namedtuple('Point', 'x, y')
Point3 = namedtuple('Point', 'x y')
Point4 = namedtuple('Point', 'x y x class', rename=True) # Default는 False -> 에러 발생
In [113]:
print(Point4)
<class '__main__.Point'>
In [114]:
print(Point1, Point2, Point3, Point4)
<class '__main__.Point'> <class '__main__.Point'> <class '__main__.Point'> <class '__main__.Point'>
In [115]:
# 객체 생성
p1 = Point1(x=10, y=35)
p2 = Point2(20, 40)
p3 = Point3(45, y=20)
p4 = Point4(10, 20, 30, 40)
print()
print(p1)
print(p2)
print(p3)
print(p4) # Rename test
Point(x=10, y=35)
Point(x=20, y=40)
Point(x=45, y=20)
Point(x=10, y=20, _2=30, _3=40)
In [116]:
# Dict to Unpacking
temp_dict = {'x':75,'y':55}
p5 = Point3(**temp_dict)
In [117]:
print(p5)
Point(x=75, y=55)
In [118]:
# 사용
print(p1[0]+p2[1])
50
In [119]:
print(p1.x+p2.y)
50
In [120]:
x, y = p3
print(x,y)
45 20
In [121]:
# 네임드 튜플 메소드
temp = [52, 38]
# _make() : 새로운 객체 생성
p4 = Point1._make(temp)
# _fields : 필드 네임 확인
print(p1._fields, p2._fields)
# _asdict() : Ordered Dict 반환
print()
print(p1._asdict())
('x', 'y') ('x', 'y')
{'x': 10, 'y': 35}
In [122]:
print(p4)
Point(x=52, y=38)
In [123]:
# 사용 실습
# 반 20명, 4개의 반 (A,B,C,D)
In [124]:
Classes = namedtuple('Classes', ['rank','number'])
In [125]:
# 그룹 리스트 선언
numbers = [str(n) for n in range (1,21)]
ranks = 'A B C D'.split()
print(numbers)
print(ranks)
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20']
['A', 'B', 'C', 'D']
In [126]:
# List Comprehension
students = [Classes(rank, number) for rank in ranks for number in numbers]
In [127]:
print(len(students))
80
In [128]:
print(students)
[Classes(rank='A', number='1'), Classes(rank='A', number='2'), Classes(rank='A', number='3'), Classes(rank='A', number='4'), Classes(rank='A', number='5'), Classes(rank='A', number='6'), Classes(rank='A', number='7'), Classes(rank='A', number='8'), Classes(rank='A', number='9'), Classes(rank='A', number='10'), Classes(rank='A', number='11'), Classes(rank='A', number='12'), Classes(rank='A', number='13'), Classes(rank='A', number='14'), Classes(rank='A', number='15'), Classes(rank='A', number='16'), Classes(rank='A', number='17'), Classes(rank='A', number='18'), Classes(rank='A', number='19'), Classes(rank='A', number='20'), Classes(rank='B', number='1'), Classes(rank='B', number='2'), Classes(rank='B', number='3'), Classes(rank='B', number='4'), Classes(rank='B', number='5'), Classes(rank='B', number='6'), Classes(rank='B', number='7'), Classes(rank='B', number='8'), Classes(rank='B', number='9'), Classes(rank='B', number='10'), Classes(rank='B', number='11'), Classes(rank='B', number='12'), Classes(rank='B', number='13'), Classes(rank='B', number='14'), Classes(rank='B', number='15'), Classes(rank='B', number='16'), Classes(rank='B', number='17'), Classes(rank='B', number='18'), Classes(rank='B', number='19'), Classes(rank='B', number='20'), Classes(rank='C', number='1'), Classes(rank='C', number='2'), Classes(rank='C', number='3'), Classes(rank='C', number='4'), Classes(rank='C', number='5'), Classes(rank='C', number='6'), Classes(rank='C', number='7'), Classes(rank='C', number='8'), Classes(rank='C', number='9'), Classes(rank='C', number='10'), Classes(rank='C', number='11'), Classes(rank='C', number='12'), Classes(rank='C', number='13'), Classes(rank='C', number='14'), Classes(rank='C', number='15'), Classes(rank='C', number='16'), Classes(rank='C', number='17'), Classes(rank='C', number='18'), Classes(rank='C', number='19'), Classes(rank='C', number='20'), Classes(rank='D', number='1'), Classes(rank='D', number='2'), Classes(rank='D', number='3'), Classes(rank='D', number='4'), Classes(rank='D', number='5'), Classes(rank='D', number='6'), Classes(rank='D', number='7'), Classes(rank='D', number='8'), Classes(rank='D', number='9'), Classes(rank='D', number='10'), Classes(rank='D', number='11'), Classes(rank='D', number='12'), Classes(rank='D', number='13'), Classes(rank='D', number='14'), Classes(rank='D', number='15'), Classes(rank='D', number='16'), Classes(rank='D', number='17'), Classes(rank='D', number='18'), Classes(rank='D', number='19'), Classes(rank='D', number='20')]