Python class - inheritance

박상영·2020년 6월 18일
0

상속(inheritance)이란?

  • class에서 상속이란, 물려주는 class(Parent class, Super class) 의 내용(attribute 와 method)을 물려받는 class(Child class, sub class)가 가지게 되는것이다.
  • 예를 들면 국가라는 class(class Country())가 있고, 그것을 상속받는 한국, 일본, 중국, 미국 등의 class를 만들수 있으며, 국가라는 class의 기본적인 속성으로 인구라는 속성을 만들었다면, 상속받는 한국, 일본, 중국 등의 class에서 Parent class의 attribute와 method를 사용할 수 있음을 말한다.
  • 기본적인 사용방법
    child class를 선언할때 ()소괄호로 Parent class를 포함시킨다.
    그러면 child class에서는 Parent class의 attribute와 method는 기재하지 않아도 포함된다.

그렇다면 상속받은 child class인 class Korea의 출력은 어떻게 될까?

country라는 변수에 child class를 저장하고
상속받은 Parent class의 show()도 호출해보았다.
Parent class안에 def show(self)함수의 print문도 출력되는것을 볼수있다.

메소드 오버라이딩(Method overriding)

  • 메소드 오버라이딩은 Parent class 의 method를 child class 에서 재정의 하는것이다.
  • 밑에 코드에서 Korea 클래스 에서 Parent class인 Country의 show method를 재정의 해보았습니다.

하지만 출력값은 Parent class의 method가 아닌 child class의 method가 출력되었다.
여기서 부모클래스의 method를 호출하려면 super()라는 키워드를 사용하면 child class에서도 parent class를 호출할수있다.
super().show()를 child class method인 show 에 추가했더니 a.show()로 호출하게되어도 같이 출력되는것을 볼수있다.

상속받은 parent class가 무엇이있는지 알아보고 싶을때는 child class.mro()를 사용한다.
그렇다면 바로 보도록하자. print(Korea.mro()) 를 출력해보면


모든 class는 object 클래스의 상속이라는것을 알수있다.

profile
backend

0개의 댓글