本文介绍了如何在 sympy 中扩展 Symbol 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 sympy 中扩展 Symbol 类时遇到问题.这可能是一般类扩展的结果,也可能是这个特定的符号"类的问题.

I’m having trouble extending the Symbol class in sympy. It could be a result of something with class extensions in general, or it might also be an issue with this specific "Symbol" class.

我想扩展 Symbol 类以拥有一个名为boolean_attr"的附加属性,它是一个 True/False 属性.这模拟了我正在尝试做的事情:

I want to extend the Symbol class to have an additional attribute called "boolean_attr" which is a True/False attribute. This simulates what I’m trying to do:

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 中尝试此操作时,这就是我所做的:

So, when I try this in Sympy this is what I do:

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 类添加属性?谢谢.

How do I add an attribute to the Symbol class in sympy? Thanks.

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

(Additionally, I should mention that this might be an xy problem without me knowing it. I want to know how to add an attribute to a class, and my question assumes that extending the class is the best way to do that. If this is an incorrect assumption, please let me know)

推荐答案

我能够通过更仔细地检查 SymPy 中的 Symbol 类来解决这个问题.__new__ 方法将一个名为 'name' 的字符串作为输入,因此我们至少需要在子类中对 Super 的调用中使用它:

I was able to fix this by more carefully examining the Symbol class in SymPy. The __new__ method takes as input a string called 'name', and so we at least need that in the call to Super in the subclass:

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__() 需要 2 个参数(给出 3 个) (https://pastebin.com/P5VmD4w4)

Furthermore, without using the keyword arguments, this fails:State('x', True) with the error TypeError: __new__() takes exactly 2 arguments (3 given) (https://pastebin.com/P5VmD4w4)

但是,如果我使用关键字参数,那么它似乎可以工作:

However if I use a keyword argument, then it appears to work:

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

这篇关于如何在 sympy 中扩展 Symbol 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:11