在sympy.printing.Printer的_print函数中可以看到一个hook,使得对于每一个类都会尝试寻找对应的_print_{class}函数来处理,因此我们只要利用好这个hook就可以为自定义类创建latex生成逻辑,我试图创建了一个_print_BoldUndefinedFunction函数,但发现它捕获不到(其实是因为BoldUndefinedFunction被包在了一个Function中,cls是Function),所以将_print_Function重写并判断其中的func是否为BoldUndefinedFunction即可。
# to represent a vector of functions as a whole
class BoldUndefinedFunction(UndefinedFunction):
pass
# Define a custom latex printer for the BoldUndefinedFunction
class CustomLatexPrinter(LatexPrinter):
def _print_Function(self, expr, exp=None):
if isinstance(expr.func, BoldUndefinedFunction):
return r'\mathbf{{{}}}\left({}\right)'.format(self._print(expr.func),
','.join(str(arg) for arg in expr.args))
else:
return super()._print_Function(expr, exp)
# use this latex instead of latex() in sympy to get bold function latex.
def latex(expr):
printer = CustomLatexPrinter()
return printer.doprint(expr)
class BoldFunction(Function):
nargs = None
def __new__(cls, *args, **kwargs):
return BoldUndefinedFunction(args[0])
标签:Function,latex,自定义,expr,BoldUndefinedFunction,生成,print
From: https://www.cnblogs.com/myendless/p/17990738