본문 바로가기

Python/객체지향 프로그래밍

(Python) 객체지향 프로그래밍 - 클래스 상속 (private)

728x90
 
class Disk(object):
    __capacity = 0
    __rpm = 0
    def __init__(self, capacity, rpm):
        self.__capacity = capacity
        self.__rpm = rpm
   
    def getCapacity(self):
        return self.__capacity
    def getRpm(self):
        return self.__rpm
    def __str__(self):
        return "디스크의 용량은 " + str(self.__capacity) + "GB"
        + " RPM은 " + str(self.__rpm)
 

 

 
from Disk import Disk

class HddDisk(Disk):
    def __init__(self, capacity, rpm):
        super().__init__(capacity,rpm)  # 얘를 해주지 않았더니 상속받는 메서드에서 capacity와 rpm 값이 0으로 나왔다!
        self.__capacity = capacity
        self.__rpm = rpm

    def __str__(self):
        return "HDD 디스크의 용량은 " + str(self.__capacity) \
            + "GB" + " RPM은 " + str(self.__rpm)
 

 

 
hdd = HddDisk(111,222)
print(hdd.getCapacity())
print(hdd.getRpm())
print(hdd)

cd = Disk(100,200)
print(cd.getCapacity())
print(cd.getRpm())
print(cd)
 

 

 

Private 함수를 쓰면 여러 예상치 못한 상황들이 발생하는 것 같았다.

1. 자손 클래스의 생성자에서 조상 클래스의 메서드를 이용하려면 조상 클래스의 생성자를 호출해야 했다.

2. 조상 클래스의 필드값이 있어야 했다. (private인 경우)