我在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)'
这将很有用,因为它使我能够跟踪所有变量并知道我要处理的物理量。这样的事情在sympy中甚至是遥不可及的吗?
编辑
我不认为这是重复的,因为符号的
__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
确实存在
.__doc__
属性,但是我无法出于自己的目的对其进行更改。它是只读的。 最佳答案
您可以继承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))
输出:
Distance (m) Time (s)
x + 2
关于python - 可以在sympy中为符号添加描述吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46021227/