如何在 sympy 中扩展 Symbol class?

How to extend Symbol class in sympy?

我在 sympy 中扩展符号 class 时遇到问题。这可能是一般 class 扩展的结果,也可能是这个特定“符号”class 的问题。

我想扩展符号 class 以具有一个名为“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 中为符号 class 添加属性?谢谢。

(另外,我应该提到这可能是一个 xy problem 而我不知道。我想知道如何将属性添加到 class,我的问题假设 扩展 class 是最好的方法。如果这是一个不正确的假设,请告诉我)

试试下面的代码,它适用于我 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__()

我能够通过更仔细地检查 SymPy 中的 Symbol class 来解决这个问题。 __new__ 方法将一个名为 'name' 的字符串作为输入,因此我们至少在子 class:

中调用 Super 时需要它
from sympy.core.symbol import Symbol
class State(Symbol):
    def __init__(self, name, boolean_attr):
        self.boolean_attr = boolean_attr
        super(State, self).__init__(name)

此外,如果不使用关键字参数,这会失败: State('x', True) 错误 TypeError: __new__() takes exactly 2 arguments (3 given) (https://pastebin.com/P5VmD4w4)

但是,如果我使用关键字参数,那么它似乎有效:

x = State('x', boolean_attr=True)