首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >这是Python中的鸭子类型吗?

这是Python中的鸭子类型吗?
EN

Stack Overflow用户
提问于 2013-06-11 00:35:37
回答 3查看 19.2K关注 0票数 11

下面是一些Ruby代码:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
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,但我看不懂。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-06-11 00:55:11

鸭子类型是关于尝试一些东西,并在发生异常时进行处理。只要它叫,就像对待鸭子一样对待它,否则,就以不同的方式对待它。

代码语言:javascript
运行
复制
try:
    dog.quack()
except AttributeError:
    dog.woof()

在描述非鸭子类型的语言之后,在wikipedia Duck_typing article的顶部解释了此行为:

在鸭子类型的语言中,等价的函数将接受任何类型的对象,并调用该对象的walk和quack方法。如果对象没有被调用的方法,则该函数发出运行时错误信号。如果对象确实有这些方法,那么无论对象的类型如何,都会执行这些方法,这会引起引用,并因此得到这种类型的名称。

对于您的示例:

代码语言:javascript
运行
复制
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!'

输出:

代码语言:javascript
运行
复制
Quaaaaaack!
Heeeelp!
Meeowww!
票数 41
EN

Stack Overflow用户

发布于 2013-06-11 00:41:59

是的,这是鸭子类型,Python代码可以(并且经常)使用它。

http://en.wikipedia.org/wiki/Duck_typing#In_Python

在页面的更上面有一个更完整的Python示例:

代码语言:javascript
运行
复制
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()
票数 5
EN

Stack Overflow用户

发布于 2013-06-11 00:43:13

在Python语言中定义方法时,必须提供应用该方法的对象,在本例中,该对象为self

因此,您必须使用以下代码行调整您的代码,以获得预期的行为:

代码语言:javascript
运行
复制
class Duck:
    def help(self):
        print("Quaaaaaack!")

class Person:
    def help(self):
        print("Heeeelp!")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17028722

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档