__str__ 在自定义 sympy Function 中的行为是什么?

huangapple go评论78阅读模式
英文:

Behavior of __str__ in a custom sympy Function?

问题

I apologize for any inconvenience. Here's the translation of the code part you provided:

我想要一个自定义的 SymPy 函数在转换为字符串时具有特殊行为行为应该像 _latex 一样

我尝试了以下代码

```python
from sympy import Function, Symbol, latex
class TestClass(Function):
    def _latex(self, printer):
        return 'This is a latex test!'
    def __str__(self):
        return 'This is a str test!'

a = TestClass(Symbol('a'))
ab = TestClass(Symbol('a')) + TestClass(Symbol('b'))

对于以下输出:

print(latex(ab))
print(str(a))

预期/期望的结果如下:

This is a latex test! + This is a latex test!
This is a str test!

然而,对于以下输出:

print(str(ab))

输出是:

TestClass(a) + TestClass(b)

如何实现所期望的行为呢?


Please note that the translation is provided only for the code part, as per your request.

<details>
<summary>英文:</summary>

I would like to have a custom SymPy Function with special behavior when it is converted to a string. The behavior should be like for _latex.

I tried the following code:

from sympy import Function, Symbol, latex
class TestClass(Function):
def _latex(self, printer):
return 'This is a latex test!'
def str(self):
return 'This is a str test!'

a = TestClass(Symbol('a'))
ab = TestClass(Symbol('a')) + TestClass(Symbol('b'))

The results for

print(latex(ab))
print(str(a))

are as expected/desired

This is a latex test! + This is a latex test!
This is a str test!

However, for

print(str(ab))

the output is

TestClass(a) + TestClass(b)


How can I archive the desired behavior?

</details>


# 答案1
**得分**: 1

```py
class TestClass(Function):
    def _sympystr(self, printer):
        return printer.doprint('This is a test!')

a = TestClass(Symbol('a'))
ab = TestClass(Symbol('a')) + TestClass(Symbol('b'))

print(a)
print(ab)

输出:

This is a test!
This is a test! + This is a test!

请注意我如何调用打印机:printer.doprint('This is a test!')。在这个简单的情况下,你可以直接返回字符串。但是,如果你的类包含其他sympy对象(符号、函数、数字等),使用这种方法可以创建标准的sympy输出。

英文:

You can define the _sympystr method, which accepts a printer.

class TestClass(Function):
    def _sympystr(self, printer):
        return printer.doprint(&#39;This is a test!&#39;)

a = TestClass(Symbol(&#39;a&#39;))
ab = TestClass(Symbol(&#39;a&#39;)) + TestClass(Symbol(&#39;b&#39;))

print(a)
print(ab)

Output:

This is a test!
This is a test! + This is a test!

Note how I called the printer: printer.doprint(&#39;This is a test!&#39;). In this simple case you could have just returned the string directly. However, if your class contains other sympy objects (symbols, functions, numbers, ...), with this method you can create standard sympy ouput.

huangapple
  • 本文由 发表于 2023年5月25日 15:50:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76330012.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定