I'm trying to make a new class called MyFunction
which is an One Variable Function.
It inherits from sympy.Function
to get the same properties, but I'm having problems with the __new__
method.
My goal is to make it work
import sympy as sp
# class definition
x = MyFunction("x")
dx = x.dt
The equivalent code, which already works:
import sympy as sp
t = sp.symbols("t")
x = sp.Function("x")(t)
dx = sp.diff(x, t)
The class that inherits from sp.Function
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)'
The received error is
self = super().__new__(cls, name)(t) # Error
TypeError: 'MyFunction' object is not callable
I tried to inherit from an another class (like sp.core.function.UndefinedFunction
), but it gives the error
AttributeError: 'x' object has no attribute 'dt'
Now I have no idea how to proceed and solve it.
CodePudding user response:
If I understand you correctly:
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)
Result:
x(t)
Derivative(x(t), t)