Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

클래스 상속은 Python에서 어떻게 작동합니까?

<시간/>

클래스의 상속

클래스를 새로 정의하는 대신 새 클래스 이름 뒤의 괄호 안에 부모 클래스를 나열하여 기존 클래스에서 파생하여 클래스를 만들 수 있습니다.

자식 클래스는 부모 클래스의 속성을 상속하며 이러한 속성을 자식 클래스에 정의된 것처럼 사용할 수 있습니다. 자식 클래스는 부모의 데이터 멤버와 메서드를 재정의할 수도 있습니다.

구문

파생 클래스는 부모 클래스와 매우 유사하게 선언됩니다. 그러나 상속받을 기본 클래스의 목록은 클래스 이름 다음에 제공됩니다 -

class SubClassName (ParentClass1[, ParentClass2, ...]):
   'Optional class documentation string'
   class_suite

예시

#!/usr/bin/python

class Parent:        # define parent class
   parentAttr = 100
   def __init__(self):
      print "Calling parent constructor"
   def parentMethod(self):
      print 'Calling parent method'
   def setAttr(self, attr):
      Parent.parentAttr = attr
   def getAttr(self):
      print "Parent attribute :", Parent.parentAttr
class Child(Parent): # define child class
   def __init__(self):
      print "Calling child constructor"
   def childMethod(self):
      print 'Calling child method'
c = Child()          # instance of child
c.childMethod()      # child calls its method
c.parentMethod()     # calls parent's method
c.setAttr(200)       # again call parent's method
c.getAttr()          # again call parent's method

출력

위의 코드가 실행되면 다음과 같은 결과가 생성됩니다 -

Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200