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.

49 lines
1.0 KiB

  1. # duck typing example taken from wikipedia
  2. # https://de.wikipedia.org/wiki/Duck-Typing
  3. class Bird:
  4. """Birds have a name that they return in string represention"""
  5. def __init__(self, name):
  6. self.name = name
  7. def __str__(self):
  8. return self.__class__.__name__+' '+self.name
  9. class Duck(Bird):
  10. """Ducks are birds which can quak"""
  11. def quak(self):
  12. print(str(self)+': quak')
  13. class Frog:
  14. """Frogs also can quak"""
  15. def quak(self):
  16. print(str(self)+': quak')
  17. def main():
  18. ducks = [Bird('Gustav'), Duck('Donald'), object()]
  19. for duck in ducks:
  20. # exception handling when object hasn't quak method
  21. try:
  22. duck.quak()
  23. except AttributeError:
  24. print('No duck:', duck)
  25. ducks.append(Frog())
  26. for duck in ducks:
  27. # we also can use hasattr() function instead of exception handling
  28. if hasattr(duck, 'quak'):
  29. duck.quak()
  30. else:
  31. print('No duck:', duck)
  32. if __name__ == "__main__":
  33. main()