【发布时间】:2011-09-28 14:38:50
【问题描述】:
我刚刚阅读了关于 duck typing 的 Wikipedia 文章,我觉得我错过了关于我在 Java 中使用的接口概念的重要一点:
"When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck."
class Duck:
def quack(self):
print("Quaaaaaack!")
def feathers(self):
print("The duck has white and gray feathers.")
def swim(self):
print("Swim seamlessly in the water")
class Person:
def quack(self):
print("The person imitates a duck.")
def feathers(self):
print("The person takes a feather from the ground and shows it.")
def name(self):
print("John Smith")
def in_the_forest(duck):
duck.quack()
duck.feathers()
def game():
donald = Duck()
john = Person()
in_the_forest(donald)
in_the_forest(john)
game()
如果我在in_the_forest 中写道:
-
quack像鸭子吗?是的 - 有鸭子
feathers吗?是的 - 太好了,我们有一只鸭子!
后来,因为我知道它是一只鸭子,所以我想要它到swim? john会沉!
我不希望我的应用程序在其过程中崩溃(随机)因为 John 假装是一只鸭子,但我想检查对象的每个属性不是一个明智的主意我收到了...?
【问题讨论】:
-
总之,你不用担心。您编写了涵盖尽可能多的代码路径和极端情况的良好测试,但 100% 的安全性永远不可能。请注意,Java 或大多数其他静态类型系统也无法获得 100% 的安全性;)
-
+1:一个关于一个重要主题的非常好的问题,有很好的答案。抱歉,我只能给它 1 票。