TUTORIAL

파이썬 튜토리얼-클래스 상속

이 섹션에서 파이썬 클래스 상속을 소개합니다

이 페이지의 내용

이 섹션에서는 Python 객체 지향 프로그래밍의 상속에 대해 배웁니다.

상속에서 자식 클래스는 부모 클래스에서 만들어집니다. 자식 클래스는 부모 클래스의 모든 것 (데이터 멤버 및 멤버 함수)을 상속합니다.

다음은 파이썬에서 상속의 문법입니다 :

class ParentClass:
    # members


class ChildClass(ParentClass):
    # members

자식 클래스에는 부모 클래스의 모든 기능이 있으며 새로운 기능도 추가 할 수 있습니다.

아래 예제와 같이 Auto라는 상위 클래스가 있으며 하위 클래스 car가 상속됩니다.

>>> class Auto:
	def __init__(self, e, n):
		self.engine = e
		self.name = n
	def display(self):
		print("Name of Auto: ", self.name)
		print("Engine of auto: ", self.engine)

		
>>> class Car(Auto):
	def __init__(self):
		self.x= input("Enter name of car: ")
		self.y= input("Enter engine of car: ")
		Auto.__init__(self,self.y,self.x)

		
>>> c = Car()
Enter name of car: Prius
Enter engine of car: 1.5l
>>> c.display()
Name of Auto:  Prius
Engine of auto:  1.5l

여기에서 Auto 클래스의 메소드를 Car 클래스에서 사용할 수 있음을 알 수 있습니다. Car 는 Auto 에서 상속되기 때문입니다.

Car 의 생성자 안에서 Auto 의 생성자가 호출됩니다. Car 의 객체는 Auto 의 모든 메소드를 호출하는 데 사용될 수 있습니다.

파이썬 클래스 상속 메소드 재정의

메서드 재정의는 자식 클래스와 부모 클래스 모두에 대해 동일한 메서드가있는 경우입니다. 메서드 재정의는 기본적으로 자식 클래스가 부모 클래스의 메서드 구현을 변경하는 개념입니다.

자식 클래스 Car 가 Auto 클래스와 동일한 display 메소드를 가지고 있지만 구현이 변경되는 예를 고려하십시오.

>>> class Auto:
	def __init__(self, e, n):
		self.engine = e
		self.name = n
	def display(self):
		print("Name of Auto: ", self.name)
		print("Engine of auto: ", self.engine)

		
>>> class Car(Auto):
	def __init__(self):
		self.x= input("Enter name of car: ")
		self.y= input("Enter engine of car: ")
		Auto.__init__(self,self.y,self.x)
    def display(self):
		print("You are in child class")

		
>>> c = Car()
Enter name of car: Prius
Enter engine of car: 1.5l
>>> c.display()
You are in child class

이제 객체 c 에서 display 메소드가 호출되면 자식 클래스의 메소드가 호출됩니다.

파이썬 클래스 다중 상속

자식 클래스에 둘 이상의 부모 클래스가있는 경우 다중 상속이 발생합니다. 각 부모 클래스의 기능은 자식 클래스에 의해 상속됩니다.

다음은 다중 상속 구문입니다.

class A:
    # members


class B:
    # members


class child(A, B):
    # members

예:

>>> class A:
	def dispA(self):
		print('You are in class A')

		
>>> class B:
	def dispB(self):
		print('You are in class B')

		
>>> class C(A, B):
	def dispC(self):
		print('You are in class C')

>>> Cobj = C()
>>> Cobj.dispA()
You are in class A

>>> Cobj.dispB()
You are in class B

>>> Cobj.dispC()
You are in class C

C (자식 클래스)의 객체는 부모 클래스 A 와 B 의 메소드를 호출 할 수 있습니다. 따라서 C 가 A 와 B 의 모든 것을 상속한다고 말할 수 있습니다.

파이썬 클래스 다단계 상속

다단계 상속은 다른 자식 클래스에서 자식 클래스를 상속하는 것입니다.

다단계 상속 구문은 다음과 같습니다.

class A:
    # members


class B(A):
    # members


class C(B):
    # members

예:

>>> class A:
	def dispA(self):
		print('You are in class A')

		
>>> class B(A):
	def dispB(self):
		print('You are in class B')

		
>>> class C(B):
	def dispC(self):
		print('You are in class C')
        
>>> Cobj = C()

>>> Cobj.dispA()
You are in class A

>>> Cobj.dispB()
You are in class B

>>> Cobj.dispC()
You are in class C

여기서 C 클래스는 부모 클래스와 조부모 클래스의 메서드를 호출 할 수 있습니다.