鸭打字

在编程中,鸭子类型是动态编程语言中使用的类型系统。对象的类型或类不如它定义的方法重要。
使用鸭子类型,您可以检查一个类是否具有给定的方法或属性。

为什么叫 Duck Typing?

它来自那句话:
如果它走路像鸭子,嘎嘎也像鸭子,那它一定是鸭子

基本上在程序的上下文中,只要一个类具有函数的确切名称;我们既不关心函数具体做什么,也不关心具体函数来自哪个类。

Is关键字_

对于鸭子类型和检查空值,我们需要使用is关键字。
is关键字用于检查给定对象的数据类型并返回一个布尔值:

  1. 5 is int # true
  2. Frog is Animal # Does the Frog Class inherit from the Animal Class and is not empty?

鸭子打字的例子

  1. # Animal Class
  2. extends Node
  3. class_name Animal
  4. func fly():
  5. print('Animal flies')
  1. # Duck Class
  2. extends Animal
  3. class_name Duck
  4. func fly():
  5. print('this duck flies')
  1. # Circle Class
  2. extends Node
  3. class_name Circle
  4. func fly():
  5. print('Circles are flying???')
  1. # Node Class
  2. extends Node2D
  3. var animal = Animal.new()
  4. var duck = Duck.new()
  5. var circle = Circle.new()
  6. # No Type Safety
  7. """
  8. In this case we can pass it in everything and the function call will work
  9. as long as the class object has that specific function name
  10. letItFly(animal)
  11. letItFly(duck)
  12. letItFly(circle)
  13. """
  14. func letItFly(flyingObject):
  15. flyingObject.fly()
  16. # With Type Safety
  17. """
  18. But what if we want type safety?
  19. Say we only want Classes and Sub-Classes of the 'Animal' class???
  20. """
  21. func animalFlies(animalObject: Animal):
  22. animalObject.fly() # comes with auto complete
  23. """
  24. The problem is that an error will be thrown if the class is a null value
  25. For Example:
  26. var nullObject: Animal # Null Instantiation w/ type safety
  27. In this case nullObject will make it through the animalFlies() method without warning.
  28. The game will crash when a null object tries to call the 'fly()' because it does not exist
  29. on a null object
  30. In this case we have to check that null values are not sneaking through
  31. """
  32. # Check for the objects casted as Nulls
  33. # var nullObject: Animal # casted as null but will make it through this function regardless
  34. func animalFliesSafely(animalObject: Animal):
  35. # Option 1
  36. if animalObject == null:
  37. print('object/value does not fly')
  38. return
  39. # Option 2
  40. if (animalObject is Animal) == false:
  41. print('Animal Class not part of Inheritance Chain')
  42. return
  43. # Do whatever you want; you're an animal!
  44. print('continue on ;)')
  45. animalObject.fly() # without a null check, throws an error if null