英文:
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('This is a test!')
a = TestClass(Symbol('a'))
ab = TestClass(Symbol('a')) + TestClass(Symbol('b'))
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('This is a test!')
. 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论