[英]SymPy: Custom print format for a custom Function expression
定义在Sympy中继承Function
类并为其创建自定义打印语句的类的正确方法是什么?
我遵循了https://docs.sympy.org/latest/modules/printing.html中的示例,这些示例修改了Mod
的输出,并且一切正常。
例如:
使用自定义打印机
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
要么
使用自定义打印方法
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
但是,当我尝试创建自己的函数时,我永远无法获得改变输出的任何一种方法。
使用自定义打印机
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
要么
使用自定义打印方法
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
有人可以帮我了解我所缺少的是什么吗?
由于Custom具有eval方法,因此Custom(a,b)
成为Mul, a*b
。 由于它不是Custom的实例,因此永远不会调用您的打印机方法。 如果重命名评估方法_eval
(以将其禁用),则print_latex(Custom(a, b))
将产生输出“ hi”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.