Why Won't Sympy Take My Symbols?
Solution 1:
The <__main__.construct object at 0x1088a5ad0>
in the error message is what is returned by the default construct.__str__()
method. I notice that once that method is overridden with one returning the string representation of construct.value
then anything that uses sympy.sympify()
(including sympy.Matrix()
) accepts it. I don't know that this is how existing custom objects are intended to be converted by SymPy--there might be a more ideal way.
import sympy
classconstruct(object):
def__init__(self, value):
self.value = value
def__add__(self, symbol):
return construct(self.value+symbol.value)
def__mul__(self,symbol):
return construct(self.value*symbol.value)
def__str__(self):
returnstr(self.value)
a = construct(2)
b = construct(10)
print(sympy.Matrix([[a],[b]])) # will output 'Matrix([[2], [10]])'
Were I to do this only with SymPy classes, I would use the following:
import sympy
a,b = sympy.symbols('a b')
a = 2
b = 10print(sympy.Matrix([[a],[b]])) # will output'Matrix([[2], [10]])'
Solution 2:
You need to subclasses SymPy's classes to create a new object to use within SymPy. Generally you subclass either Function
(for defining a function, akin to sin
or log
), or Expr
for general expressions. The class should have an args
attribute and be recreatable with obj.func(*obj.args)
(obj.func
is equal to the objects class by default).
I can't really offer more advice on specifics, as the sample class you gave is really simple, and as @Christopher Chavez has pointed out, you can just use a Symbol. But depending on what you want to do, there are various methods you can override in your subclass. A good reference is to look at the SymPy source code, as all objects that come with SymPy use this model.
Post a Comment for "Why Won't Sympy Take My Symbols?"