我寻求一种能够在需要时为符号提供描述的功能。这将是
的内容>>> x = symbols('x')
>>> x.description.set('Distance (m)')
>>> t = symbols('t')
>>> t.description.set('Time (s)')
>>> x.description()
'Distance (m)'
>>> t.description()
'Time (s)'
这很有用,因为它可以让我跟踪我的所有变量并知道我正在处理的物理量。在同情的情况下,这样的事情是否可以远程实现?
修改
我不认为这是重复的,因为符号的__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__
属性,但我无法为我的目的更改它。它是只读的。
答案 0 :(得分:6)
您可以继承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