【问题标题】:Changing only the calculation in a function仅更改函数中的计算
【发布时间】:2013-10-29 08:09:43
【问题描述】:

是否可以有一个函数,您可以在其中指定一个函数作为变量。

例如,我有两个函数遵循完全相同的过程,除了一个使用np.mean 计算平均值,另一个计算标准差,其中只有@ 987654322@不一样。

即 它将被定义: def calculate(function)

您可以在脚本中调用一个,例如:

calculate(mean) 和另外一个 calculate(std)

我只是想知道是否可以做这样的事情,它会大大减少我的脚本长度。

编辑

对不起,我应该说我希望 mean 和 std 是 numpy.xml 中预定义的。 getattr()徐的回答有效

【问题讨论】:

    标签: python function call


    【解决方案1】:

    使用getattr根据方法名获取方法对象:

    def calculate(function):
        func = getattr(np, function)
        func(...)   # do what you want
    
    calculate("mean") # calculate the average number 
    calculate("std")  # calculate the standard deviation
    

    【讨论】:

    • 谢谢@Xu Ding,我应该指定它是一个方法对象
    【解决方案2】:

    是的,这是可能的。

    例子:

    def addIt(x):
        return x+x
    
    def test(fn):
        for x in xrange(5):
            print fn(x)
    
    
    test(addIt)
    

    输出:

    0
    2
    4
    6
    8
    

    【讨论】:

      【解决方案3】:
      def f1(t): return t * 2 
      def f2(t): return t * t 
      
      def comb(t,f): return f(t)
      
      print comb(10, f1) 
      print comb(10, f2) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-07
        • 2018-02-21
        • 1970-01-01
        • 2014-10-20
        • 1970-01-01
        • 1970-01-01
        • 2023-01-26
        • 1970-01-01
        相关资源
        最近更新 更多