【问题标题】:Python intrinsic types operator overloadingPython 内在类型运算符重载
【发布时间】:2021-09-22 11:52:14
【问题描述】:

有没有办法为内在类型重载运算符?

示例:假设我想为function 类重载__mul__ 运算符:

def u(x): return cos(x)
def v(x): return sin(x)

w = u*v   # function x -> cos(x)*sin(x)

对不起,如果我没有使用正确的术语。

【问题讨论】:

    标签: python operator-overloading


    【解决方案1】:

    您无法更改内置类型,但您可以编写一个包装类,使其行为符合您的要求:

    class FuncWrapper:
        def __init__(self, f):
            self.f = f
        def __call__(self, x):
            return self.f(x)
        def __mul__(self, other):
            return FuncWrapper(lambda x: self(x) * other(x))
    

    你可以直接使用它,也可以作为装饰器使用:

    >>> from math import sin, cos, pi
    >>> sin, cos = FuncWrapper(sin), FuncWrapper(cos)
    >>> (sin * cos)(pi / 4)
    0.5
    >>> @FuncWrapper
    ... def func1(x):
    ...     return x + 1
    ... 
    >>> @FuncWrapper
    ... def func2(x):
    ...     return x + 2
    ... 
    >>> func3 = func1 * func2
    >>> func3(5)
    42
    

    【讨论】:

      【解决方案2】:

      一种方法是象征性地使用sympy

      >>> import sympy
      >>> x = sympy.Symbol('x')
      >>> u = sympy.cos(x)
      >>> v = sympy.sin(x)
      >>> u
      cos(x)
      >>> v
      sin(x)
      

      然后

      >>> w = u*v
      >>> w
      sin(x)*cos(x)
      >>> w.subs(x, 0.5)
      0.420735492403948
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-19
        • 1970-01-01
        • 1970-01-01
        • 2015-01-29
        • 2015-12-24
        相关资源
        最近更新 更多