본문 바로가기

파이썬 프로그래밍/파이썬 기초

[Python] 파이썬 super 기초 개념 및 예제

먼저 super를 사용하기전 상속, 오버라이딩 의 개념이 잡혀있어야 이해하기 쉽습니다.

(상속, 오버라이딩 클릭시 페이지 이동)



개념

super()

- 자식 클래스에서 부모클래스의 내용을 사용하고 싶을경우 사용
(무슨말인지 모르신다면 오버라이딩 편을 참고하세요)



실습

시작하기전에..


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class father():  # 부모 클래스
    def handsome(self):
        print("잘생겼다")
 
 
class brother(father):  # 자식클래스(부모클래스) 아빠매소드를 상속받겠다
    '''아들'''
 
 
class sister(father):  # 자식클래스(부모클래스) 아빠매소드를 상속받겠다
    def pretty(self):
        print("예쁘다")
 
    def handsome(self):
        '''물려받았어요'''
 
 
brother = brother()
brother.handsome()
 
girl = sister()
girl.handsome()
girl.pretty()
cs

오버라이딩 시간에 했던 내용입니다.



원래대로라면 19번째, 22번째, 23번째가 실행될떄 출력이 되서 3개가 나와야 합니다.

근데 뭔가 하나가 빠졌죠?

바로 14번째가 누락되서 22번째 출력이 되지 않은것인데요.

이것은 오버라이딩 때문에 그런것인데요.



이제 sister에서도 잘생겼다가 출력되게 해보겠습니다.



수정해봤습니다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class father():  # 부모 클래스
    def handsome(self):
        print("잘생겼다")
 
 
class brother(father):  # 자식클래스(부모클래스) 아빠매소드를 상속받겠다
    '''아들'''
 
 
class sister(father):  # 자식클래스(부모클래스) 아빠매소드를 상속받겠다
    def pretty(self):
        print("예쁘다")
 
    def handsome(self):
       super().handsome()
 
 
brother = brother()
brother.handsome()
 
girl = sister()
girl.handsome()
girl.pretty()
cs

15번째줄에 super()를 사용해 보겠습니다. (15번째 1줄만 추가했습니다)



잘 출력되죠?

super를 사용해서 상속받은 handsome에 있는 잘생겼다를 출력하게 해봤습니다.

원래는 22번째가 출력되지 않았지만 22번째도 잘 출력되는것을 확인하실 수 있습니다.



응용 실습


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class father():  # 부모 클래스
    def __init__(self, who):
        self.who = who
 
    def handsome(self):
        print("{}를 닮아 잘생겼다".format(self.who))
 
class sister(father):  # 자식클래스(부모클래스) 아빠매소드를 상속받겠다
    def __init__(self, who, where):
        super().__init__(who)
        self.where = where
 
    def choice(self):
        print("{} 말이야".format(self.where))
 
    def handsome(self):
       super().handsome()
       self.choice()
 
girl = sister("아빠""얼굴")
girl.handsome()
cs

여기서 주의하셔야 할점.

10번째줄, 17번째줄에 super()를 사용한다는 점입니다.

왜 사용해야하나?

who와 handsome()은 부모에게 물려받은 것이기 때문에 자식에서 사용하려면 무조건 super()를 사용해야 합니다.


실행