Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
906 B

  1. # small example for inhiterance with polymorphism
  2. # and duck typing as mostly better alternative
  3. class AudioFile:
  4. def __init__(self, filename):
  5. if not filename.endswith(self.ext):
  6. raise Exception("Invalid file format")
  7. self.filename = filename
  8. class MP3File(AudioFile):
  9. ext = "mp3"
  10. def play(self):
  11. print("Playing {} as mp3".format(self.filename))
  12. class WavFile(AudioFile):
  13. ext = "wav"
  14. def play(self):
  15. print("Playing {} as wav".format(self.filename))
  16. class OggFile(AudioFile):
  17. ext = "ogg"
  18. def play(self):
  19. print("Playing {} as ogg".format(self.filename))
  20. class FlacFile:
  21. def __init__(self, filename):
  22. if not filename.endswith(".flac"):
  23. raise Exception("Invalid file format")
  24. self.filename = filename
  25. def play(self):
  26. print("Playing {} as flac".format(self.filename))