简体   繁体   English

Sympy __repr__ magic - 它是如何工作的?

[英]Sympy __repr__ magic - How does it work?

I noticed that after calling init_printing method of sympy, variable's representation have a better visual appealing. 我注意到在调用init_printing方法之后,变量的表示具有更好的视觉吸引力。 I know that is usually done inheriting repr method. 我知道这通常是继承repr方法。

But when I call __repr__ method, result is different. 但是当我调用__repr__方法时,结果是不同的。 Why? 为什么?

Before init_printing being called, this is the result: init_printing之前,结果如下:

>>> import sympy as sy
>>> x = sy.Symbol('x')
>>> sy.exp(x)
exp(x)

>> sy.exp(x).__repr__()
'exp(x)'

After init_printing being called, this is the result: 调用init_printing后,结果如下:

>>> import sympy as sy
>> sy.init_printing()
>>> x = sy.Symbol('x')
>>> sy.exp(x)
 x
e

>> sy.exp(x).__repr__()
'exp(x)'

Why the repr method doesn't return the same as evaluating the representation of the variable? 为什么repr方法不会像评估变量的表示一样返回?

>>> sy.exp(x).__repr__
<bound method Basic.__repr__ of exp(x)>

That function installs a custom sys.displayhook() function , which is used in the interactive interpreter to echo the result of expressions: 该函数安装一个自定义的sys.displayhook()函数 ,该函数在交互式解释器中用于回显表达式的结果:

sys.displayhook is called on the result of evaluating an expression entered in an interactive Python session. 在评估在交互式Python会话中输入的表达式的结果上调用sys.displayhook The display of these values can be customized by assigning another one-argument function to sys.displayhook . 可以通过为sys.displayhook指定另一个单参数函数来自定义这些值的显示。

The implementation is found in the sympy.interactive.printing module : 该实现可在sympy.interactive.printing模块中找到:

 def _init_python_printing(stringify_func, **settings): """Setup printing in Python interactive session. """ import sys from sympy.core.compatibility import builtins def _displayhook(arg): """Python's pretty-printer display hook. This function was adapted from: http://www.python.org/dev/peps/pep-0217/ """ if arg is not None: builtins._ = None print(stringify_func(arg, **settings)) builtins._ = arg sys.displayhook = _displayhook 

In other words, this has nothing to do with how the objects implement __repr__ . 换句话说,这与对象如何实现__repr__

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM