我试图在numexpr表达式中使用对象属性。最明显的方法是:
import numpy as np
import numexpr as ne
class MyClass:
def __init__(self):
self.a = np.zeros(10)
o = MyClass()
o.a
b = ne.evaluate("o.a+1")结果出现以下错误
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-22-dc90c81859f1> in <module>()
10 o.a
11
---> 12 b = ne.evaluate("o.a+1")
~/.local/lib/python3.5/site-packages/numexpr/necompiler.py in evaluate(ex, local_dict, global_dict, out, order, casting, **kwargs)
799 expr_key = (ex, tuple(sorted(context.items())))
800 if expr_key not in _names_cache:
--> 801 _names_cache[expr_key] = getExprNames(ex, context)
802 names, ex_uses_vml = _names_cache[expr_key]
803 arguments = getArguments(names, local_dict, global_dict)
~/.local/lib/python3.5/site-packages/numexpr/necompiler.py in getExprNames(text, context)
706
707 def getExprNames(text, context):
--> 708 ex = stringToExpression(text, {}, context)
709 ast = expressionToAST(ex)
710 input_order = getInputOrder(ast, None)
~/.local/lib/python3.5/site-packages/numexpr/necompiler.py in stringToExpression(s, types, context)
296 names.update(expressions.functions)
297 # now build the expression
--> 298 ex = eval(c, names)
299 if expressions.isConstant(ex):
300 ex = expressions.ConstantNode(ex, expressions.getKind(ex))
<expr> in <module>()
AttributeError: 'VariableNode' object has no attribute 'a'咨询another question时,我通过使用numexpr的global_dict得到了一个不太令人满意的解决方案。
import numpy as np
import numexpr as ne
class MyClass:
def __init__(self):
self.a = np.zeros(10)
o = MyClass()
o.a
b = ne.evaluate("a+1", global_dict={'a':o.a})一旦MyClass有了十几个属性,并且有几个对ne.evaluate的调用,这就会变得非常混乱。
有一种简单干净的方法吗?
发布于 2018-10-29 22:48:37
如果对象开始具有许多属性,那么您主要关心的似乎是evaluate调用的可伸缩性/可维护性。您可以通过传递vars(o)使此部分自动化。
import numpy as np
import numexpr as ne
class MyClass:
def __init__(self):
self.a = np.arange(10000)
self.b = 2*self.a
o = MyClass()
c = ne.evaluate("a+b", local_dict=vars(o))请注意,我使用了local_dict,因为将这些名称放入本地命名空间可能会稍微快一些。如果实例属性有可能与脚本中的本地名称发生冲突(这在很大程度上取决于您如何命名属性和类的功能),那么将vars作为global_dict传递为global_dict可能更安全,就像在问题中一样(出于同样的原因,as noted in a comment)。
您仍然需要在numexpr表达式中跟踪实例属性和它们的名称之间的对应关系,但是上面的内容可以跳过大部分工作。
发布于 2018-10-29 22:52:59
您可以使用对象的__dict__属性来完成此操作。这将返回一个字典,其中键是属性的名称(作为字符串),值是该属性本身的实际值。
因此,作为一个例子,您的问题中的代码如下所示:
import numpy as np
import numexpr as ne
class MyClass:
def __init__(self):
self.a = np.zeros(10)
o = MyClass()
o.a
b = ne.evaluate("a+1", global_dict=o.__dict__) # Notice the .__dict__但是,某些对象可能没有__dict__属性。因此,相反,我做了一个小函数,可以做同样的事情:
def asdict(obj):
objDict = {}
for attr in dir(g):
objDict[attr] = getattr(g, attr)
return objDict请注意,此函数还将包括方法和某些隐藏属性,如__module__和__main__。
https://stackoverflow.com/questions/53054696
复制相似问题