问题
What is the correct way to define classes that inherit the Function class in Sympy and create custom print statements for them?
I have followed the examples from https://docs.sympy.org/latest/modules/printing.html that modify the output of Mod and it all works fine.
For example:
With a Custom Printer
from sympy import Symbol, Mod
from sympy.printing.latex import LatexPrinter
class MyLatexPrinter(LatexPrinter):
def _print_Mod(self, expr, exp=None):
return 'hey'
def print_my_latex(expr):
print(MyLatexPrinter().doprint(expr))
x = Symbol('x')
m = Symbol('m')
print_my_latex(Mod(x, m))
# prints: hey
Or
With a Custom Printing Method
from sympy import Symbol, Mod
from sympy.printing.latex import print_latex
class ModOp(Mod):
def _latex(self, printer=None):
return "hello"
x = Symbol('x')
m = Symbol('m')
print_latex(ModOp(x, m))
# prints: hello
However when I try to create my own function I can never get either method to alter the output.
With a Custom Printer
from sympy import Symbol, Function
from sympy.printing.latex import LatexPrinter
class MyLatexPrinter(LatexPrinter):
def _print_Custom(self, expr, exp=None):
return 'hi'
def print_my_latex(expr):
print(MyLatexPrinter().doprint(expr))
class Custom(Function):
@classmethod
def eval(cls, a, b):
return a * b
a = Symbol('a')
b = Symbol('b')
print_my_latex(Custom(a, b))
# prints: a b
Or
With a Custom Printing Method
from sympy import Symbol, Function
from sympy.printing.latex import print_latex
class Custom(Function):
@classmethod
def eval(cls, a, b):
return a * b
def _latex(self, printer=None):
return "howdy"
a = Symbol('a')
b = Symbol('b')
print_latex(Custom(a, b))
# prints: a b
Can someone please help me to understand what it is that I'm missing?
回答1:
Since Custom has an eval method, Custom(a,b) becomes the Mul, a*b. Since it is not an instance of Custom your printer method never gets called. If you rename your eval method _eval (to disable it) then the print_latex(Custom(a, b)) will produce the output "hi".
来源:https://stackoverflow.com/questions/55070462/sympy-custom-print-format-for-a-custom-function-expression