来自 sympy.Function 的具有预定义变量的子类

Subclass from sympy.Function with predefined variable

我正在尝试创建一个名为 MyFunction 的新 class,它是一个 单变量函数

它继承自 sympy.Function 以获得相同的属性,但我在使用 __new__ 方法时遇到问题。

我的目标是让它发挥作用

import sympy as sp
# class definition
x = MyFunction("x")
dx = x.dt

等效代码,已经可以运行:

import sympy as sp
t = sp.symbols("t")
x = sp.Function("x")(t)
dx = sp.diff(x, t)

继承自sp.Function

的class
import sympy as sp

class MyFunction(sp.Function):

    def __new__(cls, name):
        t = sp.symbols("t")
        # Now we do just like 'sp.Function("x")(t)'
        self = super().__new__(cls, name)(t)  # Error
        self.time = t
        return self

    @property
    def dt(self):
        return sp.diff(self, self.time)


x = MyFunction("x")
dx = x.dt
print(x)  # expected print 'x(t)'
print(dx)  # expected print 'Derivative(x(t), t)'

收到的错误是

self = super().__new__(cls, name)(t)  # Error
TypeError: 'MyFunction' object is not callable

我试图从另一个 class 继承(比如 sp.core.function.UndefinedFunction),但它给出了错误

AttributeError: 'x' object has no attribute 'dt'

现在我不知道如何进行和解决它。

如果我理解正确的话:

import sympy as sp

class MyFunction(sp.Function):

    def __new__(cls, name):
        t = sp.symbols("t")
        self = sp.Function(name)(t)
        self.time = t
        self.dt = sp.diff(self, self.time)
        return self

x = MyFunction("x")
dx = x.dt

print(x)
print(dx)

结果:

x(t)
Derivative(x(t), t)