-
-
Save tanakahisateru/1fd3ad7bac12d3dd7efb7fa7697bcbe5 to your computer and use it in GitHub Desktop.
What is messaging OOP in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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