16.상속(inheritance) 01
Class Inheritance(상속)
-
코드를 재사용하는 기법
-
기존에 정의해둔 클래스를 그대로 물려받는 기법
-
기존 클래스에 일부 기능을 추가하거나, 변경하여 새로운 클래스를 정의하는 기법
-
기존 클래스를 Parent, Super, Base 클래스라고 한다.
-
상속을 받는 클래는 Child, Sub, Derived 클래스라고 부른다.
순서
1.메소드 오버라이딩
2.문제 풀이
3.super
1.메소드 오버라이딩
class Car:
'''Parent Class'''
def __init__(self, _type, color):
self._type = _type
self.color = color
def show(self):
print('Car 클래스의 show메소드')
class BmwCar(Car):
def __init__(self, car_name, _type, color):
super().__init__(_type, color)
self.car_name = car_name
def show_model(self):
print('Your Car Name : %s' % self.car_name)
class Avante(Car):
def __init__(self, car_name, _type, color):
super().__init__(_type, color)
self.car_name = car_name
def show(self):
print('Avante 클래스 "show" 메소드')
def show_model(self):
print('Your Car Name : %s' % self.car_name)
# model1 = BmwCar('500d', 'sedan', 'silver')
# model1.car_name
# model1._type
# model1.show()
avante = Avante('new 아반떼', '2000cc', 'white')
avante.car_name
avante.show_model()
avante.show()
메소드 오버라이드 : 재정의
Your Car Name : new 아반떼
Avante 클래스 "show" 메소드
class Parent:
def singing(self):
print('sing a song')
father = Parent()
father.singing()
sing a song
class Child(Parent):
pass
child = Child()
child.singing()
sing a song
상속은 의미적으로 is - a 관계을 가진다
- Student is a Person
- Employee is a Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self, food):
print(f'{self.name}는 {food}를 먹습니다..')
def sleep(self, minute):
print(f'{self.name}는 {minute}분동안 잡니다..')
def work(self, minute):
print(f'{self.name}는 {minute}분동안 일합니다..')
class Student(Person):
pass
class Employee(Person):
pass
stu1 = Student('홍길북', 25)
stu1.eat('우유')
emp1 = Employee('홍길남', 30)
emp1.work('480')
홍길북는 우유를 먹습니다..
홍길남는 480분동안 일합니다..
2.문제풀이
Student 객체는 work() 호출시 “ 동안 공부합니다..”로 오버라이딩 하세요.
class Student(Person):
def work(self, minute):
print(f'{self.name}는 {minute}분동안 공부 합니다..')
kim = Student('김말똥', 24)
kim.work(120)
Employee 객체는 work() 호출시 “ 동안 사무를 봅니다..”로 오버라이딩 하세요.
class Employee(Person):
def work(self, minute):
print(f'{self.name}는 {minute}분동안 사무를 봅니다..')
emp1 = Employee('이말똥', 30)
emp1.work(300)
emp1.eat('빵')
김말똥는 120분동안 공부 합니다..
이말똥는 300분동안 사무를 봅니다..
이말똥는 빵를 먹습니다..
댓글남기기