hyeye archive
[Python] 클래스 상속 : super().__init__() 의미 본문
Python에서 "super()"는 기본적으로 다른 클래스의 속성 및 메소드를 불러와 해당 클래스에서 사용이 가능하도록 하는 기능이다. 한마디로 다른 클래스를 상속 받게 된다고 생각하면 된다.
특히, "super().__init__()" 구문은 자식 클래스에서 부모 클래스의 초기화 메소드를 호출할 때 주로 사용된다. 클래스 상속 시에, 자식 클래스는 부모 클래스의 모든 속성과 메소드를 상속받을 수 있다. 또한 필요에 따라 자식 클래스가 부모 클래스의 일부 속성을 수정하거나 확장하도록 설계할 수 있다.
자식 클래스에서 super().__init__() 을 호출하면, 부모 클래스의 초기화 메소드가 실행되어 해당 객체가 초기화된다. 이렇게 함으로써 자식 클래스는 필요한 추가적인 속성이나 메소드만 정의하면 되므로 코드 재사용성이 향상되고 효율적으로 프로그래밍을 할 수 있다.
간단한 예제를 통해서 클래스 상속에 대해서 알아 보겠다.
super().__init__()
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Animal class의 __init__ method 호출
self.breed = breed # 추가적인 속성 정의
d = Dog("Fido", "Labrador")
print(d.name) # 출력: Fido
print(d.breed) # 출력: Labrador
- Dog 이라는 자식 클래스에서 Animal 이라는 부모 클래스로부터 상속 받았고, 그 과정에서 "super().__init__(name)"을 통해 Animal 클래스의 초기화 함수를 호출했다.
- 따라서, Dog 클래스 객체가 생성될 때 name이라는 속성도 함께 초기화 되었다.
- breed라는 속성을 추가적으로 정의 했다.
super(자식클래스, self).__init__()
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
print('이름 : ', self.name)
def get_age(self):
print('나이 : ', self.age)
class Student(Person):
def __init__(self, name, age, grade):
super(Student, self).__init__(name, age)
self.grade = grade
def get_grade(self):
print('학년 : ', self.grade)
class Major(Student):
def __init__(self, name, age, grade, study):
super(Major, self).__init__(name, age, grade)
self.study = study
def get_study(self):
print('전공 : ', self.study)
student = Major('Kim', 20, 1, 'Engineering')
student.get_name()
student.get_age()
student.get_grade()
student.get_study()
이름 : Kim
나이 : 20
학년 : 1
전공 : Engineering
1. Person 클래스
- 'name'과 'age'라는 두 가지 속성을 가진 기본 클래스
- 'get_name' 및 'get_age' 메서드는 해당 속성들을 출력하는 메서드
2. Student 클래스
- Person 클래스를 상속하여 만들어진 클래스, 부모 클래스인 Person 클래스의 모든 속성과 메서드를 상속받음
- 추가로, 'grade'라는 속성을 가지고 'get_grade' 메서드로 해당 속성을 출력함.
3. Major 클래스
- Student 클래스를 상속하여 만들어진 클래스, 부모 클래스인 Student 과 그 상위의 부모 클래스인 Person 클래스의 모든 속성과 메서드를 상속받음
- 추가로, 'study'라는 속성을 가지고 'get_study' 메서드로 해당 속성을 출력함.
그런 다음, Major 클래스의 인스턴스를 생성하고 해당 인스턴스를 사용하여 메서드를 호출한다.
전체적인 계층 구조를 설명하자면 Perosn → Student → Major 순서로 상속을 진행되고 super().__init__() 코드를 통해 부모 클래스의 초기화 메서드를 호출하여 모든 클래스에서 상속받은 속성들을 초기화 한다.
super(자식클래스, self).__init__() 의 의미는 자식 클래스가 상속받는 부모 클래스를 자식 클래스에 불러오겠다는 의미이다. super().__init__()과 기능은 동일하다.
super(부모클래스, self).__init__()
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
print('이름 : ', self.name)
def get_age(self):
print('나이 : ', self.age)
class Student(Person):
def __init__(self, name, age, grade):
super(Student, self).__init__(name, age)
self.grade = grade
def get_grade(self):
print('학년 : ', self.grade)
class Major(Student):
def __init__(self, name, age, study):
super(Student, self).__init__(name, age)
self.study = study
def get_study(self):
print('전공 : ', self.study)
student = Major('Kim', 20, 'Engineering')
student.get_name()
student.get_age()
student.get_study()
student.get_grade()
기존 예시는 Perosn → Student → Major 순서로 상속 받아 왔었다.
본 예시는 3번째 Major 클래스에서
super(Major, self).__init__() 대신에 super(Student, self)__init__() 으로 바꿔보았다.
본래 자식 클래스에서 super(자식클래스, self).__init__() 의 의미는 상속받는 부모 클래스를 자식 클래스에 불러오겠다는 의미인데, 위와 같이 super(부모클래스, self)__init__() 는 부모클래스의 상위 부모클래스를 상속 받겠다는 의미가 된다.
즉, Major 클래스애서 super(Student, self)__init__() 는 자식클래스(=Major)에서 부모클래스(=Student)를 상속 받는게 아니라, Student의 부모 클래스인 Person 클래스의 속성과 메소드를 상속받게 된다.
** 요약
class 클래스 이름 (부모 클래스 이름):
부모 클래스의 속성 및 메서드를 상속하기 위한 코드
super().__init__()
상속받은 부모 클래스의 초기화 메서드를 실행시키고 속상 및 메서드를 불러오기 위한 코드
super(클래스명, self).__init__()
클래스명의 부모 클래스를 상속받기 위한 코드, 자식 클래스 이름이 될 수도 있고 부모 클래스 이름이 될 수도 있음
'Programming > Python' 카테고리의 다른 글
[Python] 케라스(Keras) 모델 훈련 .fit 함수의 verbose (0) | 2023.10.23 |
---|---|
[Python] 클래스(class)와 객체(object), 인스턴스(instance), 생성자(constructor), 메소드(method) 의미 (0) | 2023.06.08 |
[Python] Numpy의 np.clip() 사용법 (0) | 2023.03.13 |
[Python] Pandas의 pd.get_dummies() 사용법 (0) | 2022.07.12 |
[Python] Pandas의 pd.read_csv() 사용법/csv 파일 불러오기 (0) | 2022.07.08 |