[Python응용] 5. 상속과 다형성

상속의 정의와 활용

상속의 정의

상속받은 부모 클래스의 생성자를 명시적으로 호출하는 방법

class Person:
  def __init__(self, name, phoneNumber):
    self.name = name
    self.phoneNumber = phoneNumber
  def printInfo(self):
    print("Info(Name:{0}, Phone Number: {1})".format(self.name, self.phoneNumber))

class Student(Person):
  "자식 클래스"
  def __init__(self, name, phoneNumber, subject, studentID):
    Person.__init__(self, name, phoneNumber)
    self.subject = subject
    self.studentID = studentID

p = Person("전우치", "010-222-1234")
s = Student("이순신", "010-111-1234", "컴공", "991122")
print(p.__dict__)
print(s.__dict__)

다형성

class Person:
  def __init__(self, name, phoneNumber):
    self.name = name
    self.phoneNumber = phoneNumber
  def printInfo(self):
    print("Info(Name:{0}, Phone Number: {1})".format(self.name, self.phoneNumber))

class Student(Person):
  "자식 클래스"
  def __init__(self, name, phoneNumber, subject, studentID):
    Person.__init__(self, name, phoneNumber)
    self.subject = subject
    self.studentID = studentID
  def printInfo(self):
    print("Info(Name: {0}, Phone Number: {1})".format(self.name, self.phoneNumber))
    print("Info(Subject: {0}, StudentID: {1})".format(self.subject, self.studentID))

s = Student("전우치", "010-222-1234", "역사학과", "992222")
s.printInfo()
Info(Name:전우치, Phone Number: 010-222-1234)
Info(Subject:역사학과, StudentID: 992222)