파이썬 클래스의 상속
class 클래스 이름(상속할 클래스 이름)
>> 클래스 상속 하는 이유 ? 기존 클래스를 변경하지 않고, 기능을 추가하거나, 변경하기 위해서 사용
기존 클래스는 라이브러리 형태로 제공되거나, 수정이 허용되지 않는 형태로 제공되는 경우가 많다.
상속 예시 코드:
class FourCal:
def __init__(self,first,second):
self.first = first
self.second = second
def setdata(self,first, second):
self.first=first
self.second = second
def add(self):
result = self.first + self.second
return result
.
.
.class MoreFourCal(FourCal) : //상속
def pow(self):
result = self.first ** self.second
return result
a = MoreFourCal(4,2) // 2가 아니라 0으로 나누기를 하게되면 오류가 난다
print(a.pow())
>> 위에 0 오류 해결하기 위해서는 나누는 값이 0인 경우를 if 로 작성해주어야 한다.
class SafeFourCal(FourCal):
def div(self):
if self.second ==0:
return 0
else:
return self.first/self.second
부모 클래스에 있는 div메서드를 동일한 이름으로 다시 작성해준다. ( = 메서드 오버라이딩)
#연습문제 1
Calculator을 상속받아서 빼기연산가능한 메서드 추가하는 클래스를 만들어라
class Calculator:
def __init__(self):
self.value = 0
def add(self,val):
self.value +=val
class UpgradeCalculator(Calculator):
def minus(self,val):
self.value -=val
cal = UpgradeCalculator()
cal.add(10)
cal.minus(7)
print(cal.value)
#연습문제2
객체변수 value 가 100 이상의 값을 가질 수 없도록 제한하는 MaxLimitCalculator 클래스를 만들기
class Calculator:
def __init__(self):
self.value = 0
def add(self,val):
self.value +=val
class MaxLimitCalculator(Calculator):
def add(self,val):
self.value +=val
if self.value >= 100:
self.value =100
print("100")
else:
print(self.value)
cal = MaxLimitCalculator()
cal.add(50)
cal.add(60)
print(cal.value)