Programming/PYTHON

OOP 스럽게 Python 작성하기

우드의개발개발 2023. 5. 31. 17:48

추상 클래스의 선언과 구현 그리고 생성자 주입

class Switchable(ABC):
    @abstractmethod
    def turn_on(self):
        pass
    
    @abstractmethod
    def turn_off(self):
        pass


class LightBulb(Switchable):
    def turn_on(self):
        print("Lightbulb: turned on")
    
    def turn_off(self):
        print("Lightbulb: turned off")


class Fan(Switchable):
    def turn_on(self):
        print("Fan: turned on")
    
    def turn_off(self):
        print("Fan: turned off")


class PowerSwitch:
    def __init__(self, c: Switchable):
        self.client = c
        self.on = False
    
    def press(self):
        if self.on:
            self.client.turn_off()
        else:
            self.client.turn_on()
            self.on = True


myBulb = LightBulb()
myFan = Fan()

power_switch = PowerSwitch(myBulb)
fan_switch = PowerSwitch(myFan)

power_switch.press()
power_switch.press()

fan_switch.press()
fan_switch.press()

isinstance(myBulb, (Switchable)) #True
isinstance(myBulb, Switchable) #True

'Programming > PYTHON' 카테고리의 다른 글

map Iterable Iterator  (0) 2023.02.14
GIL(Global interpreter Lock)  (0) 2023.02.04