将未定义的参数传递给Python函数[UX驱动]
我想要一个绘图接口(我做绘图的Allllooottt),其中用户可以放入一个未定义的变量。将未定义的参数传递给Python函数[UX驱动]
所需界面
plot(ax,time,n1) # Returns Name Error
当前接口
plot(ax,'time','n1')
我明白,这可能是一个艰巨的任务,但我很好奇,如果堆栈的天才溢出可以找到一种方法来做到这一点。到目前为止,我已经尝试了一个装饰器,但那不起作用,因为函数中没有发生错误,而是发生在函数的调用中。尽管如此,我仍然对解决方案感兴趣......即使它很麻烦。
目前代码
def handleUndefined(function):
try:
return function
except NameError as ne:
print ne
except Exception as e:
print e
@handleUndefined
def plot(self,**args):
axesList = filter(lambda arg: isinstance(arg,p.Axes),args.keys())
parmList = filter(lambda arg: arg in self.parms, args.keys())
print axesList
print parmList
fig,ax = p.subplots()
plot(ax,time,n1)
我设计一个绘图接口,可能会有人让20个地块/分钟,所以它的重要的是在这里给他们少的语法。
因此,我已经放弃寻找解决方案,但低,看到我找到了解决方案。这并不明显,但我们可以依靠pythons魔术方法将这些变量实际链接到一个全局列表全部这是python找到变量的第一站。
我发现了一个解决方案,其中可以通过使用@public装饰附加的东西都: http://code.activestate.com/recipes/576993-public-decorator-adds-an-item-to-all/
从那里的解决方案是这样的
@public
class globalVariable(str):
_name = None
def __init__(self,stringInput):
self._name = stringInput
self.__name__ = self._name
def repr(self):
return self._name
# Hopefully There's a strong correlation
xaxis = globalVariable('trees')
yaxis = globalVariable('forest')
#Booya lunchtime
plot(trees,forest)
它认为是邪恶的(或至少是一个不好的做法)使用exec
但这是我能想出的字符串的值来动态创建一个变量的唯一方法是运行时之前未知:
strg = 'time' # suppose this value is received from the user via standard input
exec(strg + " = '" + strg + "'")
print time # now we have a variable called 'time' that holds the value of the string "time"
使用这种技术,你可以定义变量来动态地保存“他们自己的名字”。
这是一个很好的解决方案。我还没有回答的是如何动态地做到这一点。 感谢您的回应:) – CodeMode 2015-01-10 14:48:22
为什么你觉得你需要处理未定义的变量名称?我真的不认为这是可以解决的方式,你已经定义它。 – 2015-01-09 23:11:43
我同意你的意见。我只是想展示一个我一直在努力的解决方案。 我认为任何解决方案都需要在全局命名空间中进行。也许我可以在全局命名空间中创建虚拟参数? – CodeMode 2015-01-09 23:15:34
你只是想每次打电话都保存几个引号? – 2015-01-09 23:19:14