Pythonで抽象基底クラスを使う
code:py
class Person:
def __init__(self, name, device) -> None:
self.name = name
self.device = device
def speak(self, blabla):
print(f"{self.__class__.__name__} said '{blabla}'")
def single_left(self, obj):
print(f"person '{self.name}' ", end="")
self.device.single_left(obj)
class PointingDevice:
def single_left(self):
raise NotImplementedError
class Mouse(PointingDevice):
def single_left(self, obj):
print(f"clicked '{obj}'")
usr = Person("foo", Mouse()
foo = "bar"
usr.single_left(foo)
# person 'foo' clicked 'bar'
Mouseの中身を雑に変えてインスタンス化すると「未実装です!」と怒ってくれる
code:py
class Mouse(PointingDevice):
# single_left を実装してない
def double_left(self):
pass
# Traceback (most recent call last):
# File "/xxx/abstract.py", line 42, in <module>
# workers = [Person("foo", Mouse()),
# TypeError: Can't instantiate abstract class Mouse with abstract method single_left