问题
I have symbols defined as follows:
import sympy
class construct(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)
a = construct(2)
b = construct(10)
(the above code is runnable). Now, when I try to put them in a sympy matrix, it raises an error and I can't figure out why:
import sympy
A= sympy.Matrix([[a],[b]])
....SympifyError: Sympify of expression 'could not parse u'<__main__.construct object at 0x1088a5ad0>'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
I'm not even using strings here at all, so I'm not sure why it's complaining about a parse error.
回答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
class construct(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):
return str(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 = 10
print(sympy.Matrix([[a],[b]])) # will output 'Matrix([[2], [10]])'
回答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.
来源:https://stackoverflow.com/questions/42072430/why-wont-sympy-take-my-symbols