下面是一些Ruby代码:
class Duck
def help
puts "Quaaaaaack!"
end
end
class Person
def help
puts "Heeeelp!"
end
end
def InTheForest x
x.help
end
donald = Duck.new
john = Person.new
print "Donald in the forest: "
InTheForest donald
print "John in the forest: "
InTheForest john然后,我把它翻译成了Python:
import sys
class Duck:
def help():
print("Quaaaaaack!")
class Person:
def help():
print("Heeeelp!")
def InTheForest(x):
x.help()
donald = Duck()
john = Person()
sys.stdout.write("Donald in the forest: ")
InTheForest(donald)
sys.stdout.write("John in the forest: ")
InTheForest(john)结果是一样的。这是否意味着我的Python代码正在使用鸭子类型?我找不到一个鸭子类型的例子,所以我想在Python中可能没有鸭子类型。维基百科上有code,但我看不懂。
发布于 2013-06-11 00:55:11
鸭子类型是关于尝试一些东西,并在发生异常时进行处理。只要它叫,就像对待鸭子一样对待它,否则,就以不同的方式对待它。
try:
dog.quack()
except AttributeError:
dog.woof()在描述非鸭子类型的语言之后,在wikipedia Duck_typing article的顶部解释了此行为:
在鸭子类型的语言中,等价的函数将接受任何类型的对象,并调用该对象的walk和quack方法。如果对象没有被调用的方法,则该函数发出运行时错误信号。如果对象确实有这些方法,那么无论对象的类型如何,都会执行这些方法,这会引起引用,并因此得到这种类型的名称。
对于您的示例:
class Person:
def help(self):
print("Heeeelp!")
class Duck:
def help(self):
print("Quaaaaaack!")
class SomethingElse:
pass
def InTheForest(x):
x.help()
donald = Duck()
john = Person()
who = SomethingElse()
for thing in [donald, john, who]:
try:
InTheForest(thing)
except AttributeError:
print 'Meeowww!'输出:
Quaaaaaack!
Heeeelp!
Meeowww!发布于 2013-06-11 00:41:59
是的,这是鸭子类型,Python代码可以(并且经常)使用它。
http://en.wikipedia.org/wiki/Duck_typing#In_Python
在页面的更上面有一个更完整的Python示例:
class Duck:
def quack(self):
print("Quaaaaaack!")
def feathers(self):
print("The duck has white and gray feathers.")
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()发布于 2013-06-11 00:43:13
在Python语言中定义方法时,必须提供应用该方法的对象,在本例中,该对象为self。
因此,您必须使用以下代码行调整您的代码,以获得预期的行为:
class Duck:
def help(self):
print("Quaaaaaack!")
class Person:
def help(self):
print("Heeeelp!")https://stackoverflow.com/questions/17028722
复制相似问题