[英]Call a class attribute of a class instance from a function in python
假设我想从函数中绘制不同的类对象属性。
到目前为止,我有这个:
...
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
方法,如下所示:
d.x0 -> getattr(d, x0)
例如,如果x0 = 'qwerty'
,则getattr(d, x0)
等于d.qwerty
。
所以在你的代码中你应该使用:
...
ax[0].plot(getattr(d, x0), getattr(d, y0))
...
ax[1].plot(getattr(d, x1), getattr(d, y1))
...
文档: https : //docs.python.org/3/library/functions.html#getattr
至于xLims
和yLims
,我会将其定义为这样的字典列表:
xLims = [{}, {'left': 0.8}]
yLims = [{}, {'bottom': 0, 'top': 0.8}]
所以这将允许我通过**kwargs
方法使用它们:
...
ax[0].set_xlim(**xLims[0])
ax[0].set_ylim(**yLims[0])
...
ax[1].set_xlim(**xLims[1])
ax[1].set_ylim(**yLims[1])
...
主要思想是当您将字典传递给带有**
的函数时,键值对将被解包为键值参数。
因此,如果我理解正确,您正在尝试访问对象d
的属性u
,该属性通常通过编写du
来调用,但您希望能够在不提前定义所讨论的属性是u
情况下做到这一点。
d.x0
将查找d
一个名为x0
的属性,它与您定义的x0
无关。
在这种情况下,最接近你想要做的事情是getattr
函数: getattr(d, x0)
应该给你你想要的。
话虽如此,如果您可以避免使用它,这不是很好的做法。 我建议简单地将du
作为参数传递给plot2vars
并在可能的情况下相应地编辑plot2vars
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.