본문 바로가기

컴린이 일기장/Today I Learned

[TIL] Python class 상속과 super()

반응형

[주절주절]

-

 

[Today I Learned]

# 상속(inheritance)과 메서드 오버 라이딩(overriding)

- 클래스 상속이란 물려주는 클래스(Parent class, Super class)의 속성과 메서드를 물려받는 클래스(Child class, Sub class)가 갖게 되는 것.

- 어떤 클래스를 상속받아 클래스를 정의했을 때, 부모 클래스의 메서드를 자식 클래스에서 재정의하는 것이 메소드 오버 라이딩.

class Person:
    def show():
    	print('Person!')

class Student(Person):
    def show(self):
        print('Student!')


Hye = Student()
Hye.show()

 

# super()

super()는 자식 클래스에서 부모 클래스의 메서드를 사용하고 싶을 경우 사용한다. 아묻따 예시로 알아보자.

class Person:
    def __init__(self):
        print('Person __init__')
        
        self.hello = '안녕하세요'

class Student(Person):
    def __init__(self):
        print('Student __init__')
        
Hye = Student()
Hye.hello

Hye는 Student 객체로 Person 클래스를 상속받았음에도 hello 어트리뷰트를 갖지 않았다는 에러가 뜬다. 잘 보면 Hye를 선언할 때 'Person.__init__'이라는 메시지는 print 되지 않았음을 확인할 수 있다. 이는 곧 Person class의 __init__ 함수가 실행되지 않았다는 것을 의미한다. (∵ 오버 라이딩)

 

class Person:
    def __init__(self):
        print('Person __init__')
        
        self.hello = '안녕하세요'

class Student(Person):
    def __init__(self):
        print('Student __init__')
        super().__init__()

이번에는 Student의 init 함수에 super()를 통해 부모 클래스인 Person을 초기화(init)해보자.

'Person __init__'이 프린트되는 것을, 즉 Person 클래스의 init 함수가 실행되었음을 알 수 있다. 따라서 아래와 같은 것도 정상적으로 실행된다.

 

[질문 노트]

-

 

반응형