728x90

상속이 일어난 경우 

super를 사용할 일이 있다.

 

super(C, self).method(sth) 란

C의 상위에서부터(A->B->C 형태의 상속이라면)

B에서부터 method을 찾고 그 method의 인자로 sth을 넣어서

self, super(C, self).method(sth) line을 포함하고 있는 class의 instance에

적용하란 의미이다.

 

질문1

B에 method가 없고 A에 있다면?

->A의 method가 실행됨

B에 method가 있다면?

->B의 method가 실행됨

 

질문2

B에 method가 존재하는 것을 개발자가 미리 알고 있어서 

super(C, self).method(sth) 대신에

B.method(sth)을 쓰면 안되나?

->코드 유지보수면에 있어서 super(C, self).method(sth)가 유리(B의 class명을 바꾼다거나 등을 생각)

 

질문3

super().method(sth)의 의미는 무엇인가?

->super()는 super(현재 class, self)와 같음

즉, C라는 class 내부에 super().method(sth)했다면 super(C, self)와 같음

 

 

정리하면, super()는 현재 class 내의 method와 이름이 같은 것인데 걔가 아닌 상위 클래스의 method을 써야할 때 사용한다. 

특히 __init__ method에서 상위 class내의 __init__을 그대로 사용하고, 추가 작업을 할 때 보통 사용

즉, super().__init__(*arg)같은 형태로 많이 사용함

 

참고자료:

Python | super() in single inheritance - GeeksforGeeks

 

Python | super() in single inheritance - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

 

728x90

+ Recent posts