class
object
class 선언하기
class Person:
pass
bob = Person()
cathy = Person()
a = list()
b = list()
print(type(bob), type(cathy))
print(type(a), type(b))
# <class '__main__.Person'> <class '__main__.Person'>
# <class 'list'> <class 'list'>
init(self)
class Person:
def __init__(self):
print(self, 'is generated')
self.name = 'Kate'
self.age = 10
p1 = Person()
p2 = Person()
p1.name = 'aaron'
p1.age = 20
print(p1.name, p1.age)
# <__main__.Person object at 0x000001FD7398DDC8> is generated
# <__main__.Person object at 0x000001FD7398D848> is generated
# aaron 20
class Person:
def __init__(self, name, age=10):
# print(self, 'is generated')
self.name = name
self.age = age
p1 = Person('Bob', 30)
p2 = Person('Kate', 20)
p3 = Person('Aaron')
print(p1.name, p1.age) # Bob 30
print(p2.name, p2.age) # Kate 20
print(p3.name, p3.age) # Aaron 10
self
class Person:
def __init__(self, name, age):
print('self: ', self)
self.name = name
self.age = age
def sleep(self):
print('self:', self)
print(self.name, '은 잠을 잡니다.')
a = Person('Aaron', 20)
b = Person('Bob', 30)
print(a)
print(b)
a.sleep()
b.sleep()
"""
self: <__main__.Person object at 0x000001FD739C2C08>
self: <__main__.Person object at 0x000001FD739C2D08>
<__main__.Person object at 0x000001FD739C2C08>
<__main__.Person object at 0x000001FD739C2D08>
self: <__main__.Person object at 0x000001FD739C2C08>
Aaron 은 잠을 잡니다.
self: <__main__.Person object at 0x000001FD739C2D08>
Bob 은 잠을 잡니다.
"""
method 정의
# 1. 숫자를 하나 증가
# 2. 숫자를 0으로 초기화
class Counter:
def __init__(self):
self.num = 0
def increment(self):
self.num += 1
def reset(self):
self.num = 0
def print_current_value(self):
print('현재값은:', self.num)
c1 = Counter()
c1.print_current_value() # 현재값은: 0
c1.increment()
c1.increment()
c1.increment()
c1.print_current_value() # 현재값은: 3
c1.reset()
c1.print_current_value() # 현재값은: 0
c2 = Counter()
c2.increment()
c2.print_current_value() # 현재값은: 1
method type
class Math:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def multiply(a, b):
return a * b
class inheritance(상속)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self, food):
print('{}은 {}를 먹습니다.'.format(self.name, food))
def sleep(self, minute):
print('{}은 {}분동안 잡니다.'.format(self.name, minute))
def work(self, minute):
print('{}은 {}분동안 일합니다.'.format(self.name, minute))
class Student(Person):
def __init__(self, name, age):
self.name = name
self.age = age
class Employee(Person):
def __init__(self, name, age):
self.name = name
self.age = age
bob = Employee('Bob', 25)
bob.eat('BBQ') # Bob은 BBQ를 먹습니다.
bob.sleep(30) # Bob은 30분동안 잡니다.
bob.work(60) # Bob은 60분동안 일합니다.
method override
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self, food):
print('{}은 {}를 먹습니다.'.format(self.name, food))
def sleep(self, minute):
print('{}은 {}분동안 잡니다.'.format(self.name, minute))
def work(self, minute):
print('{}은 {}분동안 일합니다.'.format(self.name, minute))
class Student(Person):
def __init__(self, name, age):
self.name = name
self.age = age
def work(self, minute):
print('{}은 {}분동안 공부합니다.'.format(self.name, minute))
class Employee(Person):
def __init__(self, name, age):
self.name = name
self.age = age
def work(self, minute):
print('{}은 {}분동안 업무를 합니다.'.format(self.name, minute))
bob = Employee('Bob', 25)
bob.eat('BBQ') # Bob은 BBQ를 먹습니다.
bob.sleep(30) # Bob은 30분동안 잡니다.
bob.work(60) # Bob은 60분동안 업무를 합니다.
super
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self, food):
print('{}은 {}를 먹습니다.'.format(self.name, food))
def sleep(self, minute):
print('{}은 {}분동안 잡니다.'.format(self.name, minute))
def work(self, minute):
print('{}은 {}분동안 준비를 합니다.'.format(self.name, minute))
class Student(Person):
def __init__(self, name, age):
self.name = name
self.age = age
def work(self, minute):
super().work(minute)
print('{}은 {}분동안 공부합니다.'.format(self.name, minute))
class Employee(Person):
def __init__(self, name, age):
self.name = name
self.age = age
def work(self, minute):
super().work(minute)
print('{}은 {}분동안 업무를 합니다.'.format(self.name, minute))
bob = Employee('Bob', 25)
bob.eat('BBQ') # Bob은 BBQ를 먹습니다.
bob.sleep(30) # Bob은 30분동안 잡니다.
bob.work(60)
# Bob은 60분동안 준비를 합니다.
# Bob은 60분동안 업무를 합니다.
special method
# Point
# 2차원 좌표평면 각 점(x, y)
# 연산
# 두점 의 덧셈, 뺄셈 (1, 2) + (3, 4) = (4, 6)
# 한점과 숫자의 곱셈 (1, 2) * 3 = (3, 6)
# 그 점의 길이 (0,0) 부터의 거리
# x, y 값 가져오기
# 출력하기
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, pt):
new_x = self.x + pt.x
new_y = self.y + pt.y
return Point(new_x, new_y)
def __sub__(self, pt):
new_x = self.x - pt.x
new_y = self.y - pt.y
return Point(new_x, new_y)
def __mul__(self, factor):
return Point(self.x * factor, self.y * factor)
def __getitem__(self, index):
if index == 0:
return self.x
elif index == 1:
return self.y
else:
return -1
def __len__(self):
return self.x ** 2 + self.y ** 2
def __str__(self):
return '({}, {})'.format(self.x, self.y)
p1 = Point(3, 4)
p2 = Point(2, 7)
a = 1 + 2
p3 = p1 + p2
p4 = p1 - p2
# p5 = p1.multiply(3)
p5 = p1 * 3
# p1[0] -> x
# p1[1] -> y
print(p1[0]) # 3
print(p1[1]) # 4
print(p1) # (3, 4)
print(p2) # (2, 7)
print(p3) # (5, 11)
print(p4) # (1, -3)
print(p5) # (9, 12)
정규표현식(regular expression)
raw string
a = 'abcdef\n' # escapce 문자열
print(a)
b = r'abcdef\n'
print(b)
"""
abcdef
abcdef\n
"""
기본 패턴
search method
import re
m = re.search(r'abc', '123abcdef')
print(m) # None
m = re.search(r'\d\d\d\w', '112abcdef119')
print(m) # <re.Match object; span=(0, 4), match='112a'>
m = re.search(r'..\w\w', '@#$%ABCDabcd')
print(m) # <re.Match object; span=(2, 6), match='$%AB'>
metacharacters(메타 캐릭터)
import re
print(re.search(r'[cbm]at', 'aat')) # None
print(re.search(r'[0-4]haha', '7hahah')) # None
print(re.search(r'[abc.^]aron', 'daron')) # None
print(re.search(r'[^abc]aron', '0aron'))
# <re.Match object; span=(0, 5), match='0aron'>
****
re.search(r'\Sand', 'apple land banana')
# <re.Match object; span=(6, 10), match='land'>
re.search(r'\.and', '.and')
# <re.Match object; span=(0, 4), match='.and'>
.
re.search(r'p.g', 'pig') # <re.Match object; span=(0, 3), match='pig'>
반복패턴
import re
re.search(r'a[bcd]*b', 'abcbdccb')
# <re.Match object; span=(0, 8), match='abcbdccb'>
re.search(r'b\w+a', 'banana')
# <re.Match object; span=(0, 6), match='banana'>
re.search(r'i+', 'piigiii')
# <re.Match object; span=(1, 3), match='ii'>
re.search(r'pi+g', 'pg')
# None
re.search(r'pi*g', 'pg')
# <re.Match object; span=(0, 2), match='pg'>
re.search(r'https?', 'http://www.naver.com')
# <re.Match object; span=(0, 4), match='http'>
^, $
import re
re.search(r'b\w+a', 'cabana')
# <re.Match object; span=(2, 6), match='bana'>
re.search(r'^b\w+a', 'cabana')
# None
re.search(r'^b\w+a', 'babana')
# <re.Match object; span=(0, 6), match='babana'>
re.search(r'b\w+a$', 'cabana')
# <re.Match object; span=(2, 6), match='bana'>
re.search(r'b\w+a$', 'cabanap')
# None
groupoing
import re
m = re.search(r'(\w+)@(.+)', 'test@gmail.com')
print(m.group(1)) # test
print(m.group(2)) # gmail.com
print(m.group(0)) # test@gmail.com
{}
import re
re.search('pi{3,5}g', 'piiiiig')
# <re.Match object; span=(0, 7), match='piiiiig'>
미니멈 매칭(non-greedy way)
import re
re.search(r'<.+>', '<html>haha</html>')
# <re.Match object; span=(0, 17), match='<html>haha</html>'>
re.search(r'<.+?>', '<html>haha</html>')
# <re.Match object; span=(0, 6), match='<html>'>
{}
import re
re.search(r'a{3,5}', 'aaaaa')
# <re.Match object; span=(0, 5), match='aaaaa'>
re.search(r'a{3,5}?', 'aaaaa')
# <re.Match object; span=(0, 3), match='aaa'>
match
import re
re.match(r'\d\d\d', 'my number is 123')
# None
re.match(r'\d\d\d', '123 is my number')
# <re.Match object; span=(0, 3), match='123'>
re.search(r'^\d\d\d', '123 is my number')
# <re.Match object; span=(0, 3), match='123'>
findall
import re
re.findall(r'[\w-]+@[\w.]+', 'test@gmail.com haha test2@gmail.com nice test test')
# ['test@gmail.com', 'test2@gmail.com']
sub
import re
re.sub(r'[\w-]+@[\w.]+', 'great', 'test@gmail.com haha test2@gmail.com nice test test', count=1)
# 'great haha test2@gmail.com nice test test'
compile
import re
email_reg = re.compile(r'[\w-]+@[\w.]+')
email_reg.search('test@gmail.com haha good')
# <re.Match object; span=(0, 14), match='test@gmail.com'>
머신러닝과 데이터 분석 A-Z 올인원 패키지 Online. 👉 https://bit.ly/3cB3C8y