可以在sympy中为符号添加描述吗?

use*_*882 8 python sympy

我寻求一种能够在需要时为符号提供描述的功能.这将是一个类似的东西

>>> x = symbols('x')
>>> x.description.set('Distance (m)')
>>> t = symbols('t')
>>> t.description.set('Time (s)')
>>> x.description()
'Distance (m)'
>>> t.description()
'Time (s)'
Run Code Online (Sandbox Code Playgroud)

这将是有用的,因为它可以让我跟踪我的所有变量,并知道我正在处理的物理量.在这种情况下甚至可以远程实现这样的事情吗?

编辑

我不认为这是重复的,因为__doc__符号的属性似乎是不可变的.考虑以下:

>>> print(rhow.__doc__)

    Assumptions:
       commutative = True

    You can override the default assumptions in the constructor:

from sympy import symbols
A,B = symbols('A,B', commutative = False)
bool(A*B != B*A)
    True
bool(A*B*2 == 2*A*B) == True # multiplication by scalars is commutative
    True

>>> rhow.__doc__ = 'density of water'
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-87-bfae705941d2> in <module>()
----> 1 rhow.__doc__ = 'density of water'

AttributeError: 'Symbol' object attribute '__doc__' is read-only
Run Code Online (Sandbox Code Playgroud)

确实.__doc__存在属性,但我不能为了我的目的而改变它.它是只读的.

Ser*_*ity 7

您可以继承Symbol类并添加您自己的自定义属性,如下所示:

from sympy import Symbol, simplify

# my custom class with description attribute
class MySymbol(Symbol):
    def __new__(self, name, description=''):
        obj = Symbol.__new__(self, name)
        obj.description = description
        return obj

# make new objects with description
x = MySymbol('x')
x.description = 'Distance (m)'
t = MySymbol('t', 'Time (s)')
print( x.description, t.description)

# test
expr = (x*t + 2*t)/t
print (simplify(expr))
Run Code Online (Sandbox Code Playgroud)

输出:

Distance (m) Time (s)
x + 2
Run Code Online (Sandbox Code Playgroud)