鸭打字
在编程中,鸭子类型是动态编程语言中使用的类型系统。对象的类型或类不如它定义的方法重要。
使用鸭子类型,您可以检查一个类是否具有给定的方法或属性。
为什么叫 Duck Typing?
它来自那句话:
如果它走路像鸭子,嘎嘎也像鸭子,那它一定是鸭子
基本上在程序的上下文中,只要一个类具有函数的确切名称;我们既不关心函数具体做什么,也不关心具体函数来自哪个类。
Is关键字_
对于鸭子类型和检查空值,我们需要使用is关键字。
is关键字用于检查给定对象的数据类型并返回一个布尔值:
5 is int # trueFrog is Animal # Does the Frog Class inherit from the Animal Class and is not empty?
鸭子打字的例子
# Animal Classextends Nodeclass_name Animalfunc fly():print('Animal flies')
# Duck Classextends Animalclass_name Duckfunc fly():print('this duck flies')
# Circle Classextends Nodeclass_name Circlefunc fly():print('Circles are flying???')
# Node Classextends Node2Dvar animal = Animal.new()var duck = Duck.new()var circle = Circle.new()# No Type Safety"""In this case we can pass it in everything and the function call will workas long as the class object has that specific function nameletItFly(animal)letItFly(duck)letItFly(circle)"""func letItFly(flyingObject):flyingObject.fly()# With Type Safety"""But what if we want type safety?Say we only want Classes and Sub-Classes of the 'Animal' class???"""func animalFlies(animalObject: Animal):animalObject.fly() # comes with auto complete"""The problem is that an error will be thrown if the class is a null valueFor Example:var nullObject: Animal # Null Instantiation w/ type safetyIn this case nullObject will make it through the animalFlies() method without warning.The game will crash when a null object tries to call the 'fly()' because it does not existon a null objectIn this case we have to check that null values are not sneaking through"""# Check for the objects casted as Nulls# var nullObject: Animal # casted as null but will make it through this function regardlessfunc animalFliesSafely(animalObject: Animal):# Option 1if animalObject == null:print('object/value does not fly')return# Option 2if (animalObject is Animal) == false:print('Animal Class not part of Inheritance Chain')return# Do whatever you want; you're an animal!print('continue on ;)')animalObject.fly() # without a null check, throws an error if null
