[Python] 객체지향 - super()

2021. 11. 15. 20:47·Programming/Python

 

클래스, 객체, 생성자 등 객체지향에 대한 기본적인 내용

https://kairosial.tistory.com/13

 

[Python] 객체지향 - 클래스, 객체, 생성자

클래스와 객체 과자를 만드는 과자 틀이 클래스(Class)이고, 과자 틀에 의해서 만들어진 과자가 객체(Object) 클래스는 무엇인가를 계속해서 만들어 낼 수 있는 설계 도면이고, 객체는 클래스로 만

kairosial.tistory.com

 

super()

class Person:
    def __init__(self):
        print('Person __init__')
        self.hello = '안녕하세요'
 
class Student(Person):	# Person 클래스를 상속받음
    def __init__(self):
        print('Student __init__')
        self.school = '학교의 학생'
 
james = Student()
print(james.school)
print(james.hello)
Student __init__	# james = Student()로 객체를 만들때 Student 클래스의 __init__의 결과
학교의 학생	# print(james.school)의 결과

"'Student' object has no attribute 'hello'" 라는 오류 발생

상위 클래스인 Person 클래스의 __init__ 메서드가 호출되지 않고, 하위 클래스의 Student 클래스의 __init__ 메서드만 출력되었음

즉, Person 클래스의 __init__ 메서드가 호출되지 않으면 self.hello = '안녕하세요' 도 실행되지 않아서 객체변수가 만들어지지 않음

 

"super().메소드" 로 상위 클래스 초기화

이 때는 super()를 사용하여 상위 클래스의 __init__ 메서드를 호출

class Person:
    def __init__(self):
        print('Person __init__')
        self.hello = '안녕하세요'
 
class Student(Person):
    def __init__(self):
        print('Student __init__')
        super().__init__()	# super()로 상위 클래스인 Person 클래스의 __init__ 메서드 호출
        self.school = '학교의 학생'
 
james = Student()
print(james.school)
print(james.hello)
Student __init__	# james = Student()로 객체를 만들때 Student 클래스의 __init__의 결과
Person __init__		# 위의 생성자에 이어서 super().__init__()의 결과
학교의 학생	# print(james.school)의 결과
안녕하세요	# print(james.hello)의 결과 (위에서 Person 클래스의 __init__을 호출했으므로) 사용 가능

 

"super(하위 클래스 이름, 하위 클래스 객체).메서드" 로 더 명확하게 상위 클래스 초기화

class Student(Person):
    def __init__(self):
        print('Student __init__')
        super(Student, self).__init__()	# super().__init__() 와 같은 표현
        self.school = '학교의 학생'

 

상위 클래스를 초기화하지 않아도 되는 경우

하위 클래스에서 __init__ 메서드를 생략한다면 상위 클래스의 __init__ 이 자동으로 호출되므로 super()는 사용하지 않아도 됨

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

 

 


 

다른 예제

class A(object):
    def __init__(self):
        print("A")
    def hello(self):
        print("hello")

class B(A):
    def __init__(self):
        print("B")
    def hi(self):
        print("hi")
b = B()
b.hello()
B	# B클래스의 __init__ 메서드의 결과
hello	# b는 A클래스를 상속받은 B클래스의 객체이므로, A클래스의 hello 메서드의 결과

맨 위의 예제는 상위 클래스의 __init__ 메서드 안에 self.hello = '안녕하세요' 가 들어있었지만

이 예제에서는 상위 클래스에서 따로 만든 hello 메서드이기 때문에 super() 없이도 hello 메서드 사용 가능

 

b = B()
super(B, b).__init__()
B	# B클래스의 __init__ 메서드의 결과
A	# B클래스의 상위 클래스인 A클래스의 __init__ 메서드의 결과

super(하위 클래스 이름, 하위 클래스 객체).메서드 로 상위 클래스 호출

 

class A(object):
    def __init__(self):
        print("A")
    def hello(self):
        print("hello")

class B(A):
    def __init__(self):
        super().__init__()	# super(B, self).__init__() 와 같은 표현
        print("B")
    def hi(self):
        print("hi")

클래스 안에서 super()를 호출하면 매개변수를 따로 주지 않고도 상위 클래스 호출 가능

b = B()
A	# B클래스의 상위 클래스인 A클래스의 __init__ 메서드의 결과
B	# B클래스의 __init__ 메서드 중 print("B")의 결과

 

 

class C(B):	# B클래스를 상속받은 C클래스
    def __init__(self):
        super(C, self).__init__() # C클래스의 상위 클래스 호출
        print("C")
c = C()
A	# C의 상위 → B의 상위 → A의 __init__ 메서드의 결과
B	# B의 __init__ 메서드 중 print("B")의 결과
C	# C의 __init__ 메서드 중 print("C")의 결과

 

 

class C(B):	# B클래스를 상속받은 C클래스
    def __init__(self):
        super(B, self).__init__() # B클래스의 상위 클래스 호출
        print("C")
c = C()
A	# B클래스의 상위 클래스인 A클래스의 __init__ 메서드의 결과
C	# C클래스의 __init__ 메서드 중 print("C")의 결과

 

 

 


📝 참고

https://dojang.io/mod/page/view.php?id=2386 

 

파이썬 코딩 도장: 36.3 기반 클래스의 속성 사용하기

이번에는 기반 클래스에 들어있는 인스턴스 속성을 사용해보겠습니다. 다음과 같이 Person 클래스에 hello 속성이 있고, Person 클래스를 상속받아 Student 클래스를 만듭니다. 그다음에 Student로 인스

dojang.io

https://harry24k.github.io/super/

 

파이썬 Super 명령 알아보기

Harry Kim's Blog.

Harry24k.github.io

 

저작자표시 비영리 변경금지 (새창열림)

'Programming > Python' 카테고리의 다른 글

[Python] py ipynb 변환 (Jupyter Notebook 이용)  (1) 2022.04.12
Python JSON 파일(.json) 저장 및 불러오기  (1) 2022.03.03
Python Numpy Tutorial (with Jupyter and Colab)  (0) 2022.02.15
[Python] 객체지향 - 클래스, 객체, 생성자  (0) 2021.11.15
Python 지역변수, 전역변수  (1) 2021.11.11
'Programming/Python' 카테고리의 다른 글
  • Python JSON 파일(.json) 저장 및 불러오기
  • Python Numpy Tutorial (with Jupyter and Colab)
  • [Python] 객체지향 - 클래스, 객체, 생성자
  • Python 지역변수, 전역변수
카이로셜
카이로셜
  • 카이로셜
    카이로스의 시간
    카이로셜
  • 글쓰기 관리
  • 전체
    오늘
    어제
    • 분류 전체보기
      • Programming
        • Python
        • Linux
        • Git, Github
        • ML, Machine Learning
        • DL, Deep Learning
        • NLP
        • Computer Vision
        • Network
        • PyCharm
      • IT
        • Windows
        • Mac OS
        • Programs
        • 한글
        • Word
        • Excel
        • PowerPoint
      • Math & Statistics
      • English
      • Graduate School
      • etc.
      • Record
  • 블로그 메뉴

    • Github
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    도커
    맥북 단축키
    객체
    아나콘다 가상환경
    클래스
    아나콘다
    anaconda
    docker
    윈도우10
    윈도우11
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
카이로셜
[Python] 객체지향 - super()
상단으로

티스토리툴바