<aside> 💡 프로그래밍에서 ‘추상’은 특정 클래스의 기능을 이름만 지어두고 그 내용은 비워두는 것을 말합니다. 이로부터 상속받은 클래스에서 그 내용을 채우도록(구현) 해서, 같은 부모의 자식 클래스들이 특정 기능을 꼭 구현하되, 각자에게 맞는 방식으로 구현하도록 하는거죠. 파이썬에는 추상 메소드가 있습니다.
</aside>
from abc import ABC, abstractmethod
import math
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius
# ⚠️ 추상 메서드가 있는 클래스는 생성 불가
# shape = Shape()
rect = Rectangle(3, 4)
r_area, r_perm = rect.area(), rect.perimeter()
circ = Circle(5)
c_area, c_perm = circ.area(), circ.perimeter()
objs = [1, True, "Hello", rect, circ]
for obj in objs:
if isinstance(obj, Shape):
print(obj.area(), obj.perimeter())
섹션7 3강의 마지막 예제
click() 을 추상 메소드로 바꾼 것 확인from abc import ABC, abstractmethod
class Interface(ABC):
dark_mode_on = False
def __init__(self, size):
self.size = size
@abstractmethod
def click(self):
pass
@classmethod
def toggle_dark_mode(cls):
cls.dark_mode_on = not cls.dark_mode_on
print("다크모드 상태:", "ON" if cls.dark_mode_on else "OFF")
class Button(Interface):
def __init__(self, size, label):
super().__init__(size)
self.label = label
def click(self):
print(f"버튼 클릭: {self.label}")
class ToggleButton(Interface):
def __init__(self, size, is_on=False):
super().__init__(size)
self.is_on = is_on
def click(self):
self.is_on = not self.is_on
print("토글 상태:", "ON" if self.is_on else "OFF")
class DropdownMenu(Interface):
def __init__(self, size, options):
super().__init__(size)
self.options = options
def click(self):
print("드롭다운 메뉴 옵션:")
for option in self.options:
print(f"- {option}")
def select_option(self, option):
if option in self.options:
print(f"선택된 메뉴: {option}")
else:
print("해당 옵션은 메뉴에 없습니다.")
button = Button(10, "확인")
toggle_button = ToggleButton(12)
dropdown_menu = DropdownMenu(15, ["옵션 1", "옵션 2", "옵션 3"])
button.click()
toggle_button.click()
dropdown_menu.click()
Interface.toggle_dark_mode()