相关疑难解决方法(0)

它是pythonic:命名lambdas

我开始意识到python中lambda表达式的价值,特别是涉及函数式编程map,函数返回函数等等.但是,我也一直在函数中命名lambdas,因为:

  • 我需要多次使用相同的功能,不想重复代码.
  • 该功能特定于其出现的功能; 其他地方不需要它.

当我遇到满足上述标准的情况时,我一直在编写一个名为lambda的表达式,以便干燥并缩小范围功能.例如,我正在编写一个在某些numpy数组上运行的函数,我需要对传递给函数的所有数组进行适度的繁琐索引(可以很容易地放在一行上).我编写了一个名为lambda的表达式来进行索引,而不是编写整个其他函数,或者在整个函数定义中多次复制/粘贴索引.

def fcn_operating_on_arrays(array0, array1):
    indexer = lambda a0, a1, idx: a0[idx] + a1[idx]

    # codecodecode

    indexed = indexer(array0, array1, indices)

    # codecodecode in which other arrays are created and require `indexer`

    return the_answer
Run Code Online (Sandbox Code Playgroud)

这是滥用python的lambdas吗?我应该吮吸它并定义一个单独的功能吗?

编辑

可能值得链接功能内部功能.

python lambda

9
推荐指数
2
解决办法
3914
查看次数

以编程方式在Python中创建算术特殊方法(又名工厂函数HOWTO)

我的想法是创建可以求和/减去/ ...一起的特定函数对象,返回具有相同属性的新函数对象.希望这个示例代码能够证明这个想法:

from FuncObj import Func

# create some functions
quad = Func(lambda x: x**2)
cube = Func(lambda x: x**3)

# now combine functions as you like
plus = quad + cube
minus = quad - cube
other = quad * quad / cube

# and these can be called
plus(1) + minus(32) * other(5)
Run Code Online (Sandbox Code Playgroud)

我编写了以下代码,希望对此进行评论和记录,以解释我想要实现的目标.

import operator

class GenericFunction(object):
    """ Base class providing arithmetic special methods. 
        Use derived class which must implement the 
        __call__ method.
    """

    # this way …
Run Code Online (Sandbox Code Playgroud)

python factory class

5
推荐指数
1
解决办法
353
查看次数

标签 统计

python ×2

class ×1

factory ×1

lambda ×1