从python中的函数调用类实例的类属性

2024-05-15 00:21:07 发布

您现在位置: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是包含具有不同属性的类实例的列表,例如,uzT

现在,当我调用该函数时,我将xVars、yVars、xLims和yLims声明为字符串数组,这显然不起作用。但我不知道怎么称呼这些。我甚至不知道如何在手册中找到这个

plot2vars (
      deviceList, 
      xVars=['u', 'u'], yVars=['z', 'T'],  
      xLims=['', 'left=0.8'], yLims=['','bottom=0, top=0.8']
      )

Tags: 函数属性pltaxx1sety1devicelist
2条回答

也许,如果您想从xVarsyVars中获取作为字符串提供的属性,您应该使用如下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


至于xLimsyLims,我将其定义为如下词典列表:

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,该属性通常通过写入d.u来调用,但您希望能够做到这一点,而不必提前定义所讨论的属性是u

d.x0将查找名为x0d属性,该属性与您定义的x0无关

在本例中,最接近您要做的事情是getattr函数:getattr(d, x0)应该为您提供所需的内容

也就是说,如果你能避免使用它,那就不是很好的练习。我建议将d.u作为参数传递给plot2vars,并在可能的情况下相应地编辑plot2vars

相关问题 更多 >

    热门问题