可以在 sympy 中为符号添加描述吗? [英] Possible to add descriptions to symbols in sympy?
问题描述
我在 sympy 中寻找可以在需要时为符号提供描述的功能.这将类似于
<预><代码>>>>x = 符号('x')>>>x.description.set('距离(m)')>>>t = 符号('t')>>>t.description.set('时间(s)')>>>x.描述()'距离(米)'>>>t.description()'时间(秒)'这很有用,因为它使我能够跟踪我的所有变量并了解我正在处理的物理量.在 sympy 中,这样的事情甚至可以远程实现吗?
编辑
我不认为这是重复的,因为符号的 __doc__
属性似乎是不可变的.考虑以下几点:
确实存在 .__doc__
属性,但我不能出于我的目的更改它.它是只读的.
您可以继承 Symbol
类并添加您自己的自定义属性,如下所示:
from sympy import 符号,简化# 我的带有描述属性的自定义类类 MySymbol(Symbol):def __new__(self, name, description=''):obj = Symbol.__new__(self, name)obj.description = 描述返回对象# 创建带有描述的新对象x = MySymbol('x')x.description = '距离(米)'t = MySymbol('t', '时间 (s)')打印(x.description,t.description)# 测试expr = (x*t + 2*t)/t打印(简化(expr))
输出:
距离 (m) 时间 (s)× + 2
I seek a functionality in sympy that can provide descriptions to symbols when needed. This would be something along the lines of
>>> x = symbols('x')
>>> x.description.set('Distance (m)')
>>> t = symbols('t')
>>> t.description.set('Time (s)')
>>> x.description()
'Distance (m)'
>>> t.description()
'Time (s)'
This would be useful because it would enable me to keep track of all my variables and know what physical quantities I am dealing with. Is something like this even remotely possible in sympy?
EDIT
I don't think this is a duplicate because the __doc__
attribute for symbols appears to be immutable. Consider the following:
>>> 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
Indeed a .__doc__
attribute exists, but I cannot change it for my purposes. It is read only.
You may inherit Symbol
class and add your own custom property like here:
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))
Output:
Distance (m) Time (s)
x + 2
这篇关于可以在 sympy 中为符号添加描述吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!