什么是便利功能?

问题描述 投票:0回答:3

在 timeit 模块中有下面的代码 - 什么是便利函数?我用谷歌搜索并找不到好的答案:

def timeit(stmt="pass", setup="pass", timer=default_timer,
           number=default_number, globals=None):
    """Convenience function to create Timer object and call timeit method."""
    return Timer(stmt, setup, timer, globals).timeit(number)
python python-3.x
3个回答
7
投票

它是一个存在的函数,因此您不必费心自己实例化和跟踪对象。例如,在

timeit
模块中,唯一真正可以执行您想要的功能的是
Timer
对象 - 但作为程序员,您不想关心该 Timer 的生命周期,或将其带入你的命名空间。因此,这个
timeit.timeit()
函数相对匿名地创建一个
Timer
对象并调用
timeit()
,而不需要跟踪该
Timer
对象。 它只会做你想做的事,你不必担心细节 - 方便。

还有许多类似的其他函数,它们本质上是用于实例化类和运行方法的包装器 - 另一个例子是

subprocess.run()
,它创建了一个
Popen
对象,程序员也不必跟踪该对象.

另请参阅 维基百科对便捷函数的定义


1
投票

考虑一下:

animal_list = ["Bear", "Snake", "Snail"]
class_list = ["Mammal", "Reptile", "Gastropod"]

# Scenario 1
for i in range(len(animal_list)):
    animal = animal_list[i]
    class_ = class_list[i]
    print(f"A {animal} is a {class_}.")

# zip() - a convenience function - Scenario 2
for animal, class_ in zip(animal_list, class_list):
    print(f"A {animal} is a {class_}.")

产生相同的结果:

A Bear is a Mammal.
A Snake is a Reptile.
A Snail is a Gastropod.

场景1:不使用便捷功能

  • 混乱的代码;很难阅读和理解

场景2:使用便捷功能

  • 更简洁的代码等等方便

0
投票

sort()Python中的函数可以被认为是便利函数。

numbers = [6, 9, 3, 1]
numbers.sort()
print(numbers)  # Output: [1, 3, 6, 9]
© www.soinside.com 2019 - 2024. All rights reserved.