프로그래밍 문법/python

오버로딩과 오버라이딩

씩씩한 IT블로그 2020. 7. 17. 00:14
반응형

1. 오버로딩 : 이름은 같고, 매개변수의 타입과 개수만 다른 함수가 여러개 있을 때, 입력값의 형식이 맞는 함수를 적절히 찾아서 사용하는기술

* 파이썬에선 오버로딩이 불가능 하다! 같은 이름의 함수가 여러개 있으면, 가장 밑에 있는 함수가 실행됨 (덮어써지기 때문에)

 

2. 오버라이딩 : 부모클래스와 상속된 자식 클래스의 매소드이름이 같을 때 자식 클래스의 함수를 사용하는 것 (함수를 재정의하는 기술)

# 상속
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
    def mul(self):
        result = self.first * self.second
        return result
    def sub(self):
        result = self.first - self.second
        return result
    def div(self):
        result = self.first / self.second
        return result
        
# FourCal을 상속
class MoreFourCal(FourCal):
    def pow(self):
        return self.first**self.second
    # 메소드 오버라이딩 (부모 클래스와 같은 매소드가 있을 때 항상 자식클래스의 매소드가 실행된다)
    def div(self):
        if self.second==0:
            return 0
        else:
            return self.first/self.second

 

* 부모클래스의 객체

#매소드 오버라이딩
a=FourCal(4,0)
print(a.div())
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-99-7843e425a4e6> in <module>
      1 #매소드 오버라이딩
      2 a=FourCal(4,0)
----> 3 print(a.div())

<ipython-input-77-3f94eda98976> in div(self)
     17         return result
     18     def div(self):
---> 19         result = self.first / self.second
     20         return result
     21 

ZeroDivisionError: division by zero

 

* 자식클래스의 객체

b=MoreFourCal(4,0)
print(b.div())
0
반응형