我在扩展 sympy 中的 Symbol 类时遇到问题。这可能是一般类扩展的结果,也可能是这个特定“Symbol”类的问题。
我想扩展 Symbol 类以拥有一个名为“boolean_attr”的附加属性,它是 True/False 属性。这模拟了我想要做的事情:
class A(object): # This simulates what the "Symbol" class is in sympy
__slots__ = ['a']
def __init__(self, a):
self.a = a
# this simulates my extension to add a property
class B(A):
def __init__(self, boolean_attr):
self. boolean_attr = boolean_attr
这似乎按预期工作:
my_B = B(False)
print my_B.boolean_attr
>>>> False
所以,当我在 Sympy 中尝试时,我会这样做:
from sympy.core.symbol import Symbol
class State(Symbol):
def __init__(self, boolean_attr):
self.boolean_attr = boolean_attr
但这不起作用:
TypeError: name should be a string, not <type 'bool'>
如何向 sympy 中的 Symbol 类添加属性?谢谢。
(此外,我应该提到,这可能是 xy problem,而我却不知道。我想知道如何向类添加属性,并且我的问题假设扩展该类是最好的方法。如果这是一个错误的假设,请告诉我)
最佳答案
尝试以下代码,它在 python 3 上适用于我。
from sympy.core.symbol import Symbol
class State(Symbol):
def __init__(self, boolean_attr):
self.boolean_attr = boolean_attr
super()
Python 2 代码:
from sympy.core.symbol import Symbol
class State(Symbol):
def __init__(self, boolean_attr):
self.boolean_attr = boolean_attr
super(State, self).__init__()
关于python - 如何扩展sympy中的Symbol类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57228083/