为什么我们将函数作为参数传递给python

拉胡尔·兰詹(Rahul Ranjan)

我了解将函数作为参数传递给其他函数的过程,但是,由于C#背景的原因,我不了解该函数的必要性。

有人可以让我知道某些首选的方案吗?

宫城先生

将函数传递给函数允许参数化行为这与将值传递到允许参数化数据的函数相同

def is_greater(what: int, base: int):
    if what > base:  # fixed behaviour, parameterised data
       print(f'{what} is greater')

def is_valid(what: int, condition: 'Callable'):
    if condition(what):  # parameterised behaviour
       print(f'{what} is valid')

一些常见的用例包括:

  • mapfilter以及将某些行为应用于可迭代对象的其他对象。这些函数本身仅实现“应用于每个元素”部分,但是可以将其换出:

    >>> print(*map(float, ['1', '2', '3.0'])
    1.0 2.0 3.0
    

    在这种情况下,通常使用alambda来定义动态行为。

    >>> print(sorted(
    ...     ['Bobby Tables', 'Brian Wayne', 'Charles Chapeau'],
    ...     key=lambda name: name.split()[1]),  # sort by last name
    ... )
    ['Charles Chapeau', 'Bobby Tables', 'Brian Wayne']
    
  • 函数装饰器,用于包装具有其他行为的函数。

    def print_call(func):
        """Decorator that prints the arguments its target is called with"""
        def wrapped_func(*args, **kwargs):
            print(f'call {func} with {args} and {kwargs}')
            return func(*args, **kwargs)
        return wrapped_func
    
    @print_call
    def rolling_sum(*numbers, initial=0):
        totals = [initial]
        for number in numbers:
            totals.append(totals[-1] + number)
        return totals
    
    rolling_sum(1, 10, 27, 42, 5, initial=100)
    # call <function rolling_sum at 0x10ed6fd08> with ([1, 10, 27, 42, 5],) and {'initial': 100}
    

    每次您看到应用了一个装饰器的@函数都是一个高阶函数。

  • 在其他时间,上下文,条件,线程甚至进程执行的回调和有效负载。

    def call_after(delay: float, func: 'Callable', *args, **kwargs):
        """Call ``func(*args, **kwargs)`` after ``delay`` seconds"""
        time.sleep(delay)
        func(*args, **kwargs)
    
    thread = threading.Thread(
        target=call_after,  # payload for the thread is a function
        args=(1, print, 'Hello World'))
    thread.start()
    print("Let's see what happens...")
    # Let's see what happens...
    # 
    # Hello World
    
  • 传递函数而不是值可以模拟惰性计算

    def as_needed(expensive_computation, default):
        if random_condition():
           return expensive_computation()
        return default
    

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如果我们传递Python函数名,究竟将什么作为参数传递?

为什么我们将nn.Module作为参数传递给神经网络的类定义?

我们如何将字节作为关键字参数的键传递给函数?

我们可以将什么参数传递给super()?

如果我们可以简单地调用函数来实现,为什么要将函数作为参数传递给其他函数呢?

我们可以将函数作为参数传递吗

为什么我们不能整数文字传递作为参数传递给方法以字节为形式参数

为什么我们将String数组作为参数传递给main()方法,为什么没有任何集合类型或包装器类型或原始类型呢?

在jquery事件中,为什么我们将function()作为参数传递?

为什么我们在函数中传递匿名参数?

为什么我们将函数作为参数传入而不在 Django 中执行?

为什么我们不能在 JavaFX 中将属性作为参数传递给 Property#unbind()?

为什么我们不允许将纯引用参数传递给std :: thread但允许传递原始指针?

我们可以将什么所有信息作为参数传递给内联事件处理程序?

由于我们已经将模块作为参数传递,为什么为什么需要将module.exports作为参数传递?

我们如何将对象作为参数传递给对象值中的函数名?

当我们将参数传递给System.out.println()时会发生什么?

为什么我们将适配器传递给Section Indexer对象?

在C语言中,为什么我可以将函数名称(而不是指针)作为参数传递给函数?

为什么我们在getopt()函数中使用argc作为参数?

为什么我们不能使用。作为带有%>%的匿名函数中的参数

为什么我们不在JavaScript中使用数据类型作为函数参数?

为什么我们可以只用一个参数显式调用list(),却可以将多个参数传递给[]?

在创建线程时,我们在构造函数中传递的参数包含(this)为什么使用它?

为什么要截断我们必须传递“ w”作为在Ruby中打开的额外参数,为什么

我们可以将两个函数作为另一个函数的参数传递吗?

为什么我们不能将带有其他参数的{}块传递给Ruby中的方法

可以将pandas GroupBy函数作为参数传递给python函数吗?以及我该如何通过他们的论点?

为什么将“ null”作为参数传递给javascript中的函数?