상속 한 클래스가 다른 클래스의 메서드와 속성에 액세스하는 개념입니다.
- 상위 클래스는 상속되는 클래스이며 기본 클래스라고도 합니다.
- 하위 클래스는 파생 클래스라고도 하는 다른 클래스에서 상속되는 클래스입니다.
파이썬에는 두 가지 유형의 상속이 있습니다 -
- 다중 상속
- 다단계 상속
다중 상속 -
다중 상속에서는 하나의 자식 클래스가 여러 부모 클래스를 상속할 수 있습니다.
예시
class Father:
fathername = ""
def father(self):
print(self.fathername)
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
class Daughter(Father, Mother):
def parent(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
s1 = Daughter()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.parent() 출력
Father : Srinivas Mother : Anjali
다단계 상속
이러한 유형의 상속에서 클래스는 자식 클래스/파생 클래스에서 상속될 수 있습니다.
예시
#Daughter class inherited from Father and Mother classes which derived from Family class.
class Family:
def family(self):
print("This is My family:")
class Father(Family):
fathername = ""
def father(self):
print(self.fathername)
class Mother(Family):
mothername = ""
def mother(self):
print(self.mothername)
class Daughter(Father, Mother):
def parent(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
s1 = Daughter()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.family()
s1.parent() 출력
This is My family: Father : Srinivas Mother : Anjali