I am writing a library and I can create expressions using objects from my library. For example, x and y are instances from my library, and I can build expressions like:
# below is a simplified version of my class class MySymbol(object): import random _random_value = random.randint(1,4) def __init__(self, value): self.value = value def __add__(self, symbol): return MySymbol(self.value + symbol.value) def __mul__(self, symbol): return MySymbol(self.value * symbol.value) def __repr__(self): return str(self.value) def _get_random_value(self): return self._random_value x,y = sympy.symbols('x y') x = MySymbol(9) y = MySymbol(3) import sympy A = sympy.Matrix([[x,y],[x,y]]) B = sympy.Matrix([[x+y,x*y]])
This is also true for matrix operations. The sympy.Matrix class converts these elements to sympy.core.numbers.Integer when I want them to retain their MySymbol type:
BA=B*A print type(BA[0,0]) print type(x*x+y*x+x*x*y)
Now, since BA[0,0] no longer of type MySymbol , I cannot call the methods that I want on it:
BA[0,0]._get_random_value() # DOES NOT WORK >> AttributeError: 'Integer' object has no attribute '_get_random_value' expression = x*x+y*x+x*x*y expression._get_random_value() # THIS DOES WORK >> 4
How can I use matrix multiplication from sympy.Matrix , but still allow the elements of the matrix to maintain their type of class MySymbol ? and still allow access to all their methods (e.g. _get_random_value() )?
Sother
source share