假设我想从一个函数中绘制不同的类对象属性
到目前为止,我有:
...
import matplotlib.pyplot as plt
def plot2vars (deviceList, xVars, yVars, xLims, yLims, colormap=plt.cm.Spectral):
x0 = xVars[0]
x1 = xVars[1]
y0 = yVars[0]
y1 = yVars[1]
fig, ax = plt.subplots(1,2)
fig, ax = plt.subplots(1,2)
for d in deviceList: #these 'd' are the class instances...
if not d.discard:
ax[0].plot(d.x0, d.y0)
ax[0].set_xlim(xLims[0])
ax[0].set_ylim(yLims[0])
ax[1].plot(d.x1, d.y1)
ax[1].set_xlim(xLims[1])
ax[1].set_ylim(yLims[1])
plt.show()
其中,deviceList是包含具有不同属性的类实例的列表,例如,u
、z
或T
现在,当我调用该函数时,我将xVars、yVars、xLims和yLims声明为字符串数组,这显然不起作用。但我不知道怎么称呼这些。我甚至不知道如何在手册中找到这个
plot2vars (
deviceList,
xVars=['u', 'u'], yVars=['z', 'T'],
xLims=['', 'left=0.8'], yLims=['','bottom=0, top=0.8']
)
也许,如果您想从
xVars
和yVars
中获取作为字符串提供的属性,您应该使用如下getattr
方法:例如,如果
x0 = 'qwerty'
,getattr(d, x0)
等于d.qwerty
因此,在您的代码中,您应该使用:
文件:https://docs.python.org/3/library/functions.html#getattr
至于
xLims
和yLims
,我将其定义为如下词典列表:因此,这将允许我通过
**kwargs
方法使用它们:其主要思想是,当您将字典传递给具有
**
的函数时,键值对将被解压为键值参数因此,如果我理解正确,您正在尝试访问对象
d
的属性u
,该属性通常通过写入d.u
来调用,但您希望能够做到这一点,而不必提前定义所讨论的属性是u
d.x0
将查找名为x0
的d
属性,该属性与您定义的x0
无关在本例中,最接近您要做的事情是
getattr
函数:getattr(d, x0)
应该为您提供所需的内容也就是说,如果你能避免使用它,那就不是很好的练习。我建议将
d.u
作为参数传递给plot2vars
,并在可能的情况下相应地编辑plot2vars
相关问题 更多 >
编程相关推荐