鸭子打字允许元组,列表或可以像对待一样的东西

时间:2013-02-06 13:33:10

标签: python duck-typing

def foo(spam, obj_of_interest):
"""Pass a _____ and an object of interest, and return [something that does something worthwhile] """
    name = spam[0]
    quest = spam[1]
    fav_color = spam[2]
    # ... interesting code
    return obj_of_interest

你会注意到foo()可以完美地运作,无论它是作为列表传递spam,还是作为元组传递,或者实际上是对元素强制执行命令的任何事情,并且可以像一个清单。

如何在不告诉用户使用特定类型的情况下记录这一事实?

1 个答案:

答案 0 :(得分:8)

你说,

"""spam is an object that supports indexing."""