gpt4 book ai didi

python - 使用隐式类型转换实现逐点算术

转载 作者:太空宇宙 更新时间:2023-11-03 11:08:11 25 4
gpt4 key购买 nike

假设我有类 Function,它的实例是接受一个参数的可调用对象。我以直接的方式为这些类定义了逐点算法。这是我的代码的简化版本(实际上我在 __init____call__ 中有更复杂的行为,但这与这个问题无关):

class Function:
'''
>>> f = Function(lambda x : x**2)
>>> g = Function(lambda x : x + 4)
>>> h = f/g
>>> h(6)
3.6
'''
def __init__(self, func):
self.func = func
def __call__(self, value):
return self.func(value)
def __truediv__(self, other):
if isinstance(other, Function):
return Function(lambda x:self(x)/other(x))
else:
return NotImplemented
# ...

当我尝试允许隐式类型转换时,我卡住了。例如,我希望能够写:

>>> f = Function(lambda x : x ** 2)
>>> g = f+1
>>> g(5)
26

换句话说,每当我在 Function 实例旁边的算术表达式中看到一个数字对象 v 时,我想转换 vFunction(lambda x : v)

此外,我想为我的一些用户定义类型实现类似的行为(同样,每当我在带有 Function 对象的相同二进制算术表达式中看到它们时)。

虽然我当然可以使用常规和反射二元算术运算符的强力分类来编写此逻辑,每个运算符都检查 isinstance(v, numbers.Number)isinstance(v, MyUserDefinedType ),我觉得可能有更优雅的方式。

此外,如果我的设计还有任何其他可能的改进,请告诉我。 (Function 对象很少创建,但经常调用,因此性能很重要。)

编辑:

为了解决@Eric 的评论,我应该澄清我有另一个用户定义的类 Functional:

class Functional:
'''
>>> c = [1, 2, 3]
>>> f = Functional(lambda x : x + 1)
>>> f(c)
[2, 3, 4]
>>> g = Functional(lambda x : x ** 2)
>>> h = f + g
>>> h(c)
[3, 7, 13]
'''
def __init__(self, func):
self.func = func
@staticmethod
def from_function(self, function):
return Functional(function.func)
def __call__(self, container):
return type(container)(self.func(c) for c in container)
def __add__(self, other):
if isinstance(other, Functional):
return Functional(lambda x : self.func(x) + other.func(x))
else:
return NotImplemented

当我在同一算术表达式中同时看到 FunctionFunctional 实例时,我希望将 Function 隐式转换为 Functional 使用 Functional.from_function 方法。

因此,隐式类型转换层次结构是这样的:

  • 实用
  • 职能
  • 还有什么

我想隐式转换为在给定算术表达式中看到的此层次结构中的最高类型。

最佳答案

对于所有运算符(operator)来说,这样的事情会很有效:

def __truediv__(self, other):
if callable(other):
return Function(lambda x:self(x)/other(x))
else:
return Function(lambda x:self(x)/other)

关于python - 使用隐式类型转换实现逐点算术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13679481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com