Python(파이썬) - Override 알아보기




    이번 포스팅에서는 Override 기능의 대해서 알아보겠습니다


    관련글 :


    Python(파이썬) - 객체(Object) -  http://server-talk.tistory.com/210


    Python(파이썬) - 객체제작 - http://server-talk.tistory.com/212


    Python(파이썬) - Class(클레스)와 생성자 - http://server-talk.tistory.com/211


    Python(파이썬) - 인스턴스 변수와 메서드 - http://server-talk.tistory.com/213


    Python(파이썬) - 상속 - http://server-talk.tistory.com/214


    Python(파이썬) - 클래스 메서드 - http://server-talk.tistory.com/216


    Python(파이썬) - 객체와 변수 알아보기 - http://server-talk.tistory.com/217





     Python(파이썬) - Override 란?



    Overrride 란? 재정의 한다고 하며, 부모 클래스에서 정의한 메서드를 자식 클래스에서 변경하는 것입니다




    위 그림을 보시면 Multi 클래스를 보시면 Multi 클래스는 Calc 클래스에서 기능을 상속받았습니다

    즉 상속받은 Multi 클래스는 Calc의 기능을 모두 사용하게 됩니다




    그러나 Override를 하게되면 부모클래스를 사용하지 않고  상속받은 Multi 클래스에서 메서드를 재정의 하여 사용할수 있게 됩니다







     Python(파이썬) - Override 사용 해보기




    class Calc(object):
        def __init__(self, num1, num2):
            self.num1 = num1
            self.num2 = num2
        def sum(self):
            result = self.num1 + self.num2
            return result
    
    class Multi(Calc):
        def sum(self):
            result = self.num1 - self.num2
            return result
    
    C2 = Multi(20,10)
    print(C2.sum())
    


    위 코드는 출력함수(print) 부분부터 보시면 C2의 메서드(sum)을 호출하면 Multi 클래스를 실행하게 되며, Calc 클래스를 상속받았지만 Multi클래스의 재정의된 sum 메서드를 사용한 결괏값이 출력됩니다


    하지만 이러한 방법을 이용하면 상속받은 Calc 클래스의 기능을 사용하지 못하게되는 경우가 발생하게 됩니다




    class Calc(object):
        def __init__(self, num1, num2):
            self.num1 = num1
            self.num2 = num2
        def sum(self):
            result = self.num1 + self.num2
            return result
    
    class Multi(Calc):
        def sum(self):
            result = self.num1 - self.num2
            return "Multi -> %d , Calc -> %d " % (result, super().sum())
    
    C2 = Multi(20,10)
    print(C2.sum())
    



    위 코드의 Multi 클래스 sum 메서드의 리턴값을 보시면 super().sum() 메서드가 있습니다

    super() 를 사용하면 부모 클래스의 메서드를 호출할수 있습니다

    출력결과를 보시면 잘출력되는것을 확인하실 수 있습니다


    Posted by 서버이야기