这是Python中的鸭子吗?

a12*_*773 10 python duck-typing python-3.x

这是一些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
Run Code Online (Sandbox Code Playgroud)

而且,我把它翻译成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)
Run Code Online (Sandbox Code Playgroud)

结果是一样的.这是否意味着我的Python代码使用duck-typing?我找不到一个鸭子打字的例子,所以我想在Python中可能没有鸭子打字.维基百科中有代码,但我无法理解.

dan*_*lmo 41

代码没有显示整个故事.Duck打字是关于尝试某些事情并处理异常(如果它们发生).只要它嘎嘎叫,就像鸭子一样对待它,否则,对待它会有所不同.

try:
    dog.quack()
except AttributeError:
    dog.woof()
Run Code Online (Sandbox Code Playgroud)

在对非鸭类型语言的描述之后,在维基百科Duck_typing文章的顶部解释了此行为:

在duck-typed语言中,等效函数将采用任何类型的对象并调用该对象的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!'
Run Code Online (Sandbox Code Playgroud)

输出:

Quaaaaaack!
Heeeelp!
Meeowww!
Run Code Online (Sandbox Code Playgroud)


And*_*ark 5

是的,这是鸭子打字,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()
Run Code Online (Sandbox Code Playgroud)