两种功能的产物 [英] product of two functions

查看:101
本文介绍了两种功能的产物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个函数, f g 。两者都具有相同的签名:(x)。我想用相同的签名创建一个新函数 z

  def z(x):
return f(x)* g(x)

除了我希望能够写出



z = f * g ,而不是上面的代码。是否有可能?

解决方案

有趣的是,这很有可能。我前几天做了一个项目来做类似的事情。



这是: FuncBuilder



现在您只能定义变量,但您可以在帮助中使用我的元类



问题:


  • 速度很慢

  • 速度真的很慢

  • 您认为您需要这样做,但是要描述功能的方式是正确的。 / li>


您应该使用您的第一个代码。



  from funcbuilder import OperatorMachinery 

class FuncOperations(metaclass = OperatorMachinery):
def __init __(self,function):
self.func =函数
def __call __(self,* args,** kwargs):
返回self.func(* args,** kwargs)

def func(se lf,* n,oper = None):
如果不是n:
返回类型(self)(lambda x:oper(self.func(x)))
返回类型(lambda x:oper(self.func(x),n [0](x)))

FuncOperations.apply_operators([func,func])


$ b

 现在你可以这样编码: @FuncOperations 
def f(x):
return x + 1

@FuncOperations
def g(x):
return x + 2

期望的行为是:

pre > >>> z = f * g
>>> z(3)
20






I在 FuncBuilder 项目中添加了更好的版本。它适用于 FuncOperation 对象与另一个可调用对象之间的任何操作。也适用于一元操作。 :D



您可以使用它来制作如下功能:

  z = -f + g * h 


I have two functions, f and g. Both have the same signature: (x). I want to create a new function, z, with the same signature:

def z(x):
  return f(x) * g(x)

except that I'd like to be able to write

z = f * g instead of the above code. Is it possible?

解决方案

The funny thing is that it is quite possible. I made a project some days ago to do things like that.

Here it is: FuncBuilder

By now you can only define variables, but you can use my metaclass with the help of some other functions to build a class to what you want.

Problems:

  • It's slow
  • It's really slow
  • You think you want that but describing functions the way they meant to be described is the right way.

You should use your first code.

Just as a proof of concept:

from funcbuilder import OperatorMachinery

class FuncOperations(metaclass=OperatorMachinery):
     def __init__(self, function):
          self.func = function
     def __call__(self, *args, **kwargs):
          return self.func(*args, **kwargs)

def func(self, *n, oper=None):
    if not n:
        return type(self)(lambda x: oper(self.func(x)))
    return type(self)(lambda x: oper(self.func(x), n[0](x)))

FuncOperations.apply_operators([func, func])

Now you can code like that:

@FuncOperations
def f(x):
    return x + 1

@FuncOperations
def g(x):
    return x + 2

And the desired behavior is:

>>> z = f * g
>>> z(3)
20


I added a better version of it on the FuncBuilder project. It works with any operation between a FuncOperation object and another callable. Also works on unary operations. :D

You can play with it to make functions like:

z = -f + g * h

这篇关于两种功能的产物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆