강의노트 상속

조회수 475 • 댓글 0 • 수정 3일 전 크게 보기  
  • 클래스
  • 클래스

상속

상속은 기존 클래스를 기반으로 새로운 클래스를 생성한다. 생성된 인스턴스는 상위 클래스의 모든 속성과 메서드를 그대로 사용할 수 있다. 이를 통해 코드의 재사용성을 높이고, 유지보수성을 향상시킬 수 있다. 필요한 경우 새로운 속성과 메서드를 추가할 수도 있다.

class 자식클래스(부모클래스):
   def __init__(self):
      super().__init__(변수)

class A:
    def __init__(self,name):
        self.name = name
        print('A클래스 생성자 호출')
    def speak(self):
       print(self.name + ' 야옹 ')
        
class B(A):
    def __init__(self,name,varB):
        super().__init__(name)
        self.varB = varB
        print('B클래스 생성자 호출')
    def speak(self):
        print(self.name + ' 왈왈 ')    

class C(A):
    def __init__(self,name,varC):
        super().__init__(name)
        self.varC = varC
        print('C클래스 생성자 호출')

obj_A = A('Tom')
print('-----------')
obj_B = B('Tom','Bvar')
print('-----------')
obj_C = C('John','Cvar')

위의 예제에서 A 클래스는 name이라는 하나의 속성을 가지고 있다.

B클래스는 A클래스를 상속받았으며, name 속성을 상속받은 뒤 speak 메서드도 상속받았지만, 새로운 구현을 제공하여 개가 짖는 소리를 출력하도록 수정되었다.

C 클래스는 super() 함수를 사용하여 A 클래스의 생성자를 호출하고, name 속성을 초기화한다. speak 메서드는 A 클래스에서 상속받았지만, C 클래스에서 새로운 구현을 제공하여 고양이 짖는 소리를 출력한다.

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

부모 클래스에서 작성된 메서드를 자식클래스에서 다시 정의한다.

class car:
    # atribute
    def __init__(self, color, velocity):
        self.color = color
        self.velocity = velocity
        
    def speed_up(self):
        self.velocity = self.velocity + 5
    def speed_down(self):
        self.velocity = self.velocity - 5
        if self.velocity < 0:
            self.velocity = 0
            
aCar = car('Yellow',40)
bCar = car('White',50) 
cCar = car('Black',60)

class Sedan(car):
    def __init__(self,color, velocity, capacity):
        car.__init__(self, color, velocity)
        self.capacity = capacity
        
    def speed_up(self):
        self.velocity = self.velocity + 10
    def speed_down(self):
        self.velocity = self.velocity - 10
        
class Truck(car):
    def __init__(self,color,velocity, capacity):
        car.__init__(self, color, velocity)
        self.capacity = capacity
    def speed_up(self):
        self.velocity = self.velocity + 1
        
myCar = Sedan('Red',180,4)
truck = Truck('Blue', 60,1000)     
class Person:
    def __init__(self, name, age, gender):
        self.Name = name
        self.Age = age
        self.Gender = gender
        
    def aboutMe(self):
        print(f'나의 이름은 {self.Name}이고, 나이는 {self.Age}살 입니다.')

p1 = Person('순신',16,'남성')
p1.aboutMe()        

class Student(Person):
    def __init__(self, name, age, gender, school):
        Person.__init__(self, name, age, gender)
        self.School = school
    def school(self, major):
        self.Major = major
    def aboutMe(self):
        print(f'나의 학교는 {self.School}이고 나의 전공은 {self.major}이다.')

p2 = Student('문덕',27,'남성','전주대')        
p2.school('전기과')        
p2.aboutMe()        
이전 글
다음 글
댓글
댓글로 소통하세요.