본문 바로가기
Python/Python

[Python] 상속

by 기록하는_사람 2022. 10. 11.

상속

📌 상속

: 부모 클래스의 속성을 자식 클래스가 물려 받는 것.

 

📌 장점

① 각 클래스마다 동일한 코드 사용되는 것을 방지할 수 있음.

② 유지 보수 용이.

③ 다형성.

 

💡 다형성(Polymorphism)

: 하나의 객체가 여러 가지 타입을 가질 수 있는 것.

 

메서드 재정의(오버라이딩)

📌 메서드 재정의(오버라이딩)

: 파이썬에서는 두 메서드의 이름만 같으면 재정의가 가능함.

class Person:
    def __init__(self, name, birth, phone):
        self.Name = name
        self.Birth = birth
        self.Phone = phone
    
    def PrintInfo(self):
        print(self.Name, self.Birth, self.Phone)

class Student(Person):
    def __init__(self, name, birth, phone, subject):
        Person.__init__(self, name, birth, phone)
        self.Subject = subject

    def PrintInfo(self):
        print(self.Name, self.Birth, self.Phone, self.Subject)
    
p = Person("J", "19921204", "010-1234-5678")
s = Student("L", "20000220", "010-9876-5432", "Computer Science")

p.PrintInfo() # J 19921204 010-1234-5678
s.PrintInfo() # L 20000220 010-9876-5432 Computer Science

 

다중 상속

📌 다중 상속

: 여러 개 상속 가능.

 

💡 super() 

: 상위 클래스 메서드 호출.

class Food:
    def __init__(self):
        print("Food __init__()")

class Coffee:
    def __init__(self):
        super().__init__()
        print("Coffee __init__()")
    
    def Espresso(self):
        print("espresso")

class Icecream:
    def __init__(self):
        super().__init__()
        print("Icecream __init__()")

    def Vanila(self):
        print("vanila icecream")

class Affogato(Coffee, Icecream):
    def __init__(self):
        super().__init__()
        print("Affogato __init__()")

    def Eat(self):
        print("eat affogato")

a = Affogato()

print()
a.Espresso() 
a.Vanila() 
a.Eat() 

# Icecream __init__()
# Coffee __init__()
# Affogato __init__()

# espresso
# vanila icecream
# eat affogato

댓글