클래스 상속 (14:40)
Class inheritance
- 기존 정의해둔 클래스의 기능 물려받을 수 있음의미적으로 is-a 관계를 갖는다
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):
pass
## Person 부모 class 상속받는다.
bob = Student('Bob', 25)
## Person 부모 class 기능 ㅋ사용하기
bob.work(200)
'''
Bob은 200분 동안 일합니다.
Bob은 200분 동안 공부합니다.
'''
클래스 연산자 재정의 이해 (18:00)
# Point
# 2차원 좌표평면 각 점(x, y)
# 두 점의 덧셈, 뺄셈 (1,2) + (3,4) = (4,6)
# 한점과 숫자의 곱셈
# 그 점의 길이 (0,0)부터
# x, y 값 가져오기
# 출력하기
class Point:
def __init__(self, x,y):
self.x = x
self.y = y
def __str__(self):
return ('{}, {}'.format(self.x, self.y))
# custom print function
def print_pt(self):
print ('{}, {}'.format(self.x, self.y))
# add
# input : pt
# output : new pt
def add(self, pt):
new_x = self.x + pt.x
new_y = self.y + pt.y
return Point(new_x, new_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 multifly(self, factor):
return Point(self.x * factor, self.y * factor)
def __mul__(self, factor):
new_x = self.x * factor
new_y = self.y * factor
return Point(new_x, new_y)
def __len__(self):
return self.x **2 + self.y **2
def __getitem__(self, index):
if index == 0 :
return self.x
elif index == 1:
return self.y
else:
return -1
p1 = Point(3,4)
p2 = Point(2,7)
# custom print p1, p2
#p1.print_pt()
#p2.print_pt()
# general print function
print(p1)
# p1.add(p2)
p3 = p1.add(p2)
print(p3)
# + 연산자 overriding
p4 = p1 + p2
print (p4)
# - 연산자 overriding
p5 = p1 - p2
print (p5 )
# multifly
p6 = p1 * 2
print('p6 : ', p6)
# len
print (len(p6))
# poing type index 적용하기
# p1[0] -> x, p1[1] -> y
# point 객체 경우 index를 지원하지 않는다
print ('p6[0]==>',p6[0])
print ('p6[1]==>', p6[1])
'''
3, 4
5, 11
5, 11
1, -3
p6 : 6, 8
100
p6[0]==> 6
p6[1]==> 8
'''
'DS > fast campus daily report' 카테고리의 다른 글
7.11 (데이터엔지니어링) 클래스 연습문제 풀이, 정규표현식 연습문제 풀이 (0) | 2020.07.11 |
---|---|
7.9 (데이터엔지니어링) 정규표현식과 re모듈의 사용 (0) | 2020.07.09 |
7.7 (데이터엔지니어링) 생성자(_init_)이해 및 사용하기, self 키워드의 이해 및 사용하기, method, static method 정의 및 사용하기 (0) | 2020.07.07 |
7.6 (데이터엔지니어링) 모듈의 이해 및 사용과 import 방법, 클래스 오브젝트 이해하기, 클래스 정의 및 사용하기 (0) | 2020.07.06 |
7.5 (데이터엔지니어링) 컬렉션 타입 이해 -3 (tuple), 함수 연습 문제 풀이 (0) | 2020.07.05 |