[Python] 상속(Inheritance)

2023. 7. 17. 23:02

Person 클래스는 name 인스턴스 속성을 가지고, 생성자가 호출될 때 지정된다.

introduce 메소드는 name 속성을 print 한다.

class Person():
    def __init__(self, name):
        self.name = name

    def introduce(self):
        print(f"Hello. My name is {self.name}.")
sam = Person("sam")
sam.introduce() # Hello. My name is sam.

Person 클래스를 상속받는 자식 클래스 Student를 생성해보자. Student는 Person의 name 속성을 갖고, 새로운 studentID 속성을 가지는 클래스로 생성할 것이다.

class Student(Person):
    def __init__(self, studentID):
        self.studentID = studentID

    def introduce(self):
        print(f"Hello. My name is {self.name}. My student ID is {self.studentID}")
minji = Student('2023000000')
minji.introduce() # AttributeError: 'Student' object has no attribute 'name'

하지만 위 코드를 실행하면 Student object에 name 속성이 존재하지 않는다고 오류가 발생한다.

인스턴스 속성은 상속되지 않기 때문이다.

따라서 super() 를 이용해 부모 클래스를 생성해주어야 한다.

super(children, self).__init__(): children의 부모 클래스를 불러오겠다.

super().__init__() 도 사용 가능하다.

class Student(Person):
    def __init__(self, name, studentID):
        super(Student, self).__init__(name)
        self.studentID = studentID

    def introduce(self):
        print(f"Hello. My name is {self.name}. My student ID is {self.studentID}")
minji = Student('minji', '2023000000')
minji.introduce() # Hello. My name is minji. My student ID is 2023000000

참고
[ Python 3 ] super(클래스, self)._init_() 에 대해 제대로 알아보자!!

BELATED ARTICLES

more