Notice
Recent Posts
Recent Comments
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
10-11 00:15
Archives
Today
Total
관리 메뉴

Developer_Neo

[python] 클래스 상속, 메소드 오버라이딩, __init__ 메소드의 오버라이딩 본문

프로그래밍/Python

[python] 클래스 상속, 메소드 오버라이딩, __init__ 메소드의 오버라이딩

_Neo_ 2022. 1. 19. 23:53
반응형

파이썬의 클래스 역시 상속이라는 것을 할 수 있다.

class Father:
    def run(self):
        print("so fast!!!")

class Son(Father):
    def jump(self):
        print("so high!!!")

def main():
    s = Son()
    s.run()
    s.jump()

main()

'''
so fast!!!
so high!!!
'''

위의 코드를 보면 클래스가 Father와 Son이 있는 것을 볼 수 있다.

여기에서 상속이라는 것을 했는데

바로 class Son(Father): 이 문장이었다.

이렇게 상속을 하게 되면 Son은 자식클래스이자 서브, 하위클래스가 되고 Father는 부모클래스이자 슈퍼, 상위 클래스가 된다.

따라서 Son클래스를 이용해서 만든 객체는 Father의 메소드도 호출이 가능해진다.

 

 

상속을 하는데 있어서 한번에 둘이상의 클래스를 상속하는 것도 가능하다.

class Father:
    def run(self):
        print("so fast!!!")

class Mother:
    def dive(self):
        print("so deep!!")

class Son(Father, Mother):
    def jump(self):
        print("so high!!!")

def main():
    s = Son()
    s.run()
    s.dive()
    s.jump()

main()

위의 코드와 같이  class Son(Father, Mother):  이런식으로 작성하게 되면 Son은 2개의 클래스를 부모클래스로 두게 된다.

 


메소드 오버라이딩

상속 관계에 있어서 부모클래스가 가지는 메소드와 동일한 이름의 메소드를 자식 클래스가 정의하는 경우가 있는데 이것을 오버라이딩이라고 한다.

 

class Father:
    def run(self):
        print("so fast, dad style")

class Son(Father):
    def run(self):
        print("so fast, son style")

def main():
    s = Son()
    s.run()

main()

위와 같이 run메소드에 대한 것을 오버라이딩 한 것이다.

 

그런데 오버라이딩을 시켰지만 부모클래스에 있는 오버라이딩 시키기전 메소드를 사용하고 싶을 수도 있다.

 

이때에는 super()를 사용하면 된다.

 

class Father:
    def run(self):
        print("so fast, dad style")

class Son(Father):
    def run(self):
        print("so fast, son style")

    def run2(self):
        super().run()

def main():
    s = Son()
    s.run()
    s.run2()

main()

위의 코드와 같이 run2메소드에 super().run() 을 호출하게 되면 부모클래스의 run메소드가 호출되는 셈이 된다,

 

이렇게 되면 Son클래스로 만들어진 객체에는 2개의 run메소드를 가지고 있는 상태가 된다.

 


 

__init__ 메소드의 오버라이딩

__init__ 메소드도 오버라이딩이 가능하다는 것으로 위의 것과 똑같이 super()를 사용하면 된다. 

예제로 학습해보자

class Car:
    def __init__(self, id, f):
        self.id = id       
        self.fuel = f      

    def drive(self):
        self.fuel -= 10     

    def add_fuel(self, f):  
        self.fuel += f

    def show_info(self):
        print("id:", self.id)
        print("fuel:", self.fuel)

class Truck(Car):
    def __init__(self, id, f, c):
        super().__init__(id, f)
        self.cargo = c

    def add_cargo(self, c):
        self.cargo += c

    def show_info(self):       # 현재 차의 상태
        super().show_info()
        print("cargo:", self.cargo)


def main():
    t = Truck("42럭5959", 0, 0)
    t.add_fuel(100)
    t.add_cargo(50)
    t.drive()
    t.show_info()

main()

위와 같이 Car라는 클래스를 상속하는 Truck클래스의 __init__메소드를 보자

 

__init__메소드는 생성자에 해당하는 것인데 이것도 역시 오버라이딩이 가능하다는 것이다.

 

하는 방법부모클래스의 인자들 + 자식클래스의 인자 들을 매개변수로 받고

 

부모클래스의 인자들을 상속한 클래스인 Car의 __init__메소드로 설정해준다.

 

즉 super().__init__(부모클래스의 인자들)을 통해 설정해주면 오버라이딩이 가능하게 된다.

 

따라서 자식 클래스의 __init__은 부모의 변수를 초기화할 값도 함께 전달받아야하는데 하는 법은 super().__init__에 해당

 

하는 것으로 실행한다.

 

참고한 책 : 윤성우의 열혈 파이썬 중급편

반응형
Comments