这是Python的鸭嘴式吗? [英] Is this duck-typing in Python?

查看:133
本文介绍了这是Python的鸭嘴式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一些Ruby代码:

Here is some Ruby code:

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:

And, I translated it to 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中可能没有鸭子式的例子.维基百科中有代码,但我听不懂.

The result is the same. Does this mean my Python code is using duck-typing? I couldn't find a duck-typing example, so I thought there may be no duck-typing in Python. There is code in Wikipedia, but I couldn't understand it.

推荐答案

该代码未显示全部内容.鸭式打字是关于尝试某些事情并处理异常(如果发生).只要发出嘎嘎声,就象鸭子一样对待它,否则,请别样对待它.

The code does not show the whole story. Duck typing is about trying something and handling exceptions if they occur. As long it quacks, treat it like a duck, otherwise, treat it differently.

try:
    dog.quack()
except AttributeError:
    dog.woof()

此行为在 Wikipedia Duck_typing文章的顶部进行了说明,后面是对非-duck型语言:

This behavior is explained at the top of the wikipedia Duck_typing article following a description of a non-duck-typed language:

在鸭子类型的语言中,等效函数将采用任何类型的对象并调用该对象的walk和quack方法.如果对象不具有被调用的方法,则该函数将发出运行时错误信号.如果对象确实具有这些方法,则无论对象的类型如何,都将执行它们,从而引起引号,并因此引起这种键入形式的名称.

In a duck-typed language, the equivalent function would take an object of any type and call that object's walk and quack methods. If the object does not have the methods that are called then the function signals a run-time error. If the object does have the methods, then they are executed no matter the type of the object, evoking the quotation and hence the name of this form of typing.

以您的示例为例:

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!

这篇关于这是Python的鸭嘴式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆