Skip to content

Instantly share code, notes, and snippets.

@tanakahisateru
Created September 6, 2023 17:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanakahisateru/1fd3ad7bac12d3dd7efb7fa7697bcbe5 to your computer and use it in GitHub Desktop.
Save tanakahisateru/1fd3ad7bac12d3dd7efb7fa7697bcbe5 to your computer and use it in GitHub Desktop.
What is messaging OOP in Python
from abc import ABC, abstractmethod
from typing import Iterable
class Soundable(ABC):
@abstractmethod
def sound(self) -> str:
pass
def sound_all(soundables: Iterable[Soundable]):
for soundable in soundables:
print(soundable.sound())
###############################################
class Animal(ABC):
pass
class Duck(Animal, Soundable):
def sound(self) -> str:
return "πŸ¦† < quack"
class Dog(Animal, Soundable):
def sound(self) -> str:
return "πŸ• < bow!!"
print("Animals")
sound_all([Duck(), Dog()])
# NG sound_all([Duck(), Dog(), Fish()])
###############################################
class Toy(ABC):
pass
class ToyDuck(Toy, Soundable):
def sound(self) -> str:
return "πŸ€– < quack"
class ToyDog(Toy, Soundable):
def sound(self) -> str:
return "πŸ€– < bow!!"
print("Toys")
sound_all([ToyDuck(), ToyDog()])
###############################################
print("Mixed Soundables")
sound_all([Duck(), Dog(), ToyDuck(), ToyDog()])
###################### γŠγΎγ‘
# ...でももしこうγͺると?
class Fish(Animal):
pass
class ToyFish(Toy):
pass
all = [Duck(), Dog(), Fish(), ToyDuck(), ToyDog(), ToyFish()]
# list[Soundable] γ¨γ―θ¨€γˆγͺい
def only_soundables_of(items: Iterable) -> Iterable[Soundable]:
return filter(lambda item: isinstance(item, Soundable), items)
print("Mixed Soundables (safer)")
sound_all(only_soundables_of(all))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment