- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
假设我有类 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
时,我想转换 v
到 Function(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
当我在同一算术表达式中同时看到 Function
和 Functional
实例时,我希望将 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/
我是一名优秀的程序员,十分优秀!