【发布时间】:2013-06-06 09:28:10
【问题描述】:
这是一些 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,但是我看不懂。
【问题讨论】:
-
Python 完全是关于鸭子类型的。你写的例子很典型。
-
@darxsys 那么为什么没有这样的例子呢?维基百科上有一个代码,但我不明白它是如何工作的
标签: python python-3.x duck-typing