Python Level 2 Ch.3

phillip yoonΒ·2021λ…„ 6μ›” 27일
0

πŸ“Œ Chapter 3


πŸ’‘ Code

# Special Method(Magic Method)
# 파이썬의 핡심 -> μ‹œν€€μŠ€(Sequence), 반볡(Iterator), ν•¨μˆ˜(functions), 클래슀(Class)
# κΈ°λ³Έν˜•
print(int)
print(float)

# λͺ¨λ“  속성 및 λ©”μ†Œλ“œ 좜λ ₯
print(dir(int))
print(dir(float))
print()
print()

n=10
# μ‚¬μš©
print(n+100)
print(n.__add__(100))
# print(n.__doc__)
print(n.__bool__(), bool(n))
print(n * 100, n.__mul__(100))
print()
print()

# 클래슀 예제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__ Method.')
        return self._price + x._price
    def __sub__(self,x):
        print('Called >> __sub__ Method.')
        return self._price - x._price
    def __le__(self,x):
        print('Called >> __sub__ Method.')
        return self._price <= x._price
    def __ge__(self,x):
        print('Called >> __sub__ Method.')
        return self._price >= x._price

# μΈμŠ€ν„΄μŠ€ 생성
s1 = Fruit('Orange',7500)
s2 = Fruit('Banana', 3000)

# λ§€μ§λ©”μ†Œλ“œ 좜λ ₯
print(s1 + s2)
print(s1 - s2)
print(s1 >= s2)
print(s1 <= s2)
print(s1)
print(s2)
# Special Method(Magic Method)
# 파이썬의 핡심 -> μ‹œν€€μŠ€(Sequence), 반볡(Iterator), ν•¨μˆ˜(functions), 클래슀(Class)
# ν΄λž˜μŠ€μ•ˆμ— μ •μ˜ν•  수 μžˆλŠ” νŠΉλ³„ν•œ(Built-in) λ©”μ†Œλ“œ
# 클래슀 예제2
class Vector:
    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):
        '''Returns the vector informations'''
        return 'Vector(%r,%r)' % (self._x,self._y)
    def __add__(self,other):
        '''Returns the vector addition of self and other'''
        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))

# μΈμŠ€ν„΄μŠ€ 생성
v1 = Vector(5,7)
v2 = Vector(23,35)
v3 = Vector(0,0)
# λ§€μ§λ©”μ†Œλ“œ 좜λ ₯
print(Vector.__init__.__doc__)
print(Vector.__repr__.__doc__)
print(Vector.__add__.__doc__)
print(v1, v2, v3)
print(v1 + v2)
print(v1 * 10)
print(v2 * 3)
print(bool(v1), bool(v2))
print(bool(v3))
print()
print()
# μ°Έκ³  : 파이썬 λ°”μ΄νŠΈ μ½”λ“œ μ‹€ν–‰
import dis
dis.dis(v2.__add__)
# Special Method(Magic Method)
# 파이썬의 핡심 -> μ‹œν€€μŠ€(Sequence), 반볡(Iterator), ν•¨μˆ˜(functions), 클래슀(Class)
# ν΄λž˜μŠ€μ•ˆμ— μ •μ˜ν•  수 μžˆλŠ” νŠΉλ³„ν•œ(Built-in) λ©”μ†Œλ“œ

# 객체 -> Python의 데이터λ₯Ό 좔상화
# λͺ¨λ“  객체 -> id, type -> value

# 일반적인 νŠœν”Œ
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)

# λ„€μž„λ“œ νŠœν”Œ μ‚¬μš©
from collections import namedtuple

# λ„€μž„λ“œ νŠœν”Œ μ„ μ–Έ
Point = namedtuple('Point', 'x y')

pt3 = Point(1.0, 5.0)
pt4 = Point(2.5, 1.5)

# print(pt3)
# print(pt4)
l_leng2 = sqrt((pt3.x - pt4.x) ** 2 + (pt3.y - pt4.y) ** 2)
print(l_leng2)

# λ„€μž„λ“œ νŠœν”Œ μ„ μ–Έ 방법
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

# Dict to Unpacking
temp_dict = {'x' : 75, 'y' : 55}
print(Point1, Point2, Point3, Point4)
# 객체 생성
p1 = Point1(x = 10, y = 35)
p2 = Point2(x= 20, y = 40)
p3 = Point3(x= 45, y = 20)
p4 = Point4(10, 20, 30, 40)
p5 = Point3(**temp_dict)

print()
print(p1)
print(p2)
print(p3)
# rename
print(p4)
print(p5)

# μ‚¬μš©
print(p1[0] + p2[1])
print(p1.x + p2.y)

# Unpacking
x, y = p3
print(x + y)
# λ„€μž„λ“œ νŠœν”Œ λ©”μ†Œλ“œ
temp = [52, 38]
# _make() : μƒˆλ‘œμš΄ 객체 생성
p6 = Point1._make(temp)
print(p6)

# fields : ν•„λ“œ λ„€μž„ 확인
print(p1._fields, p2._fields, p3._fields)
# _asdict : OrderedDict λ°˜ν™˜
print(p1._asdict(), p6._asdict())

# μ‹€μ‚¬μš© μ‹€μŠ΅
# 반 20λͺ…, 4개의 반(A,B,C,D)
Classes = namedtuple('Classes', ['rank', 'number'])

# κ·Έλ£Ή 리슀트 μ„ μ–Έ
numbers = [str(n) for n in range(1,21)]
ranks = 'A B C D'.split()

# List Comprehension
students = [Classes(rank, number) for rank in ranks for number in numbers]

print(len(students))
print(students)

# μΆ”μ²œ
students2 = [
    Classes(rank, number)
    for rank in 'A B C D'.split()
        for number in [str(n)
            for n in range(1,21)]]

print(len(students2))
print(students2)

# 좜λ ₯
for s in students2:
    print(s)
profile
세상이 더 λ‚˜μ•„μ§€κΈ°λ₯Ό λ°”λΌλŠ” 마음으둜 κ°œλ°œμ— μž„ν•˜κ³  μžˆμŠ΅λ‹ˆλ‹€.

0개의 λŒ“κΈ€