簡體   English   中英

從python中的函數調用類實例的類屬性

[英]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 是一個包含具有不同屬性的類實例的列表,例如uzT

現在,當我調用該函數時,我將 xVars、yVars、xLims、yLims 聲明為字符串數組,這顯然不起作用。 但我不知道如何稱呼這些。 而且我什至不知道如何在手冊中查找此內容...

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

也許,如果您想從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 ,該屬性通常通過編寫du來調用,但您希望能夠在不提前定義所討論的屬性是u情況下做到這一點。

d.x0將查找d一個名為x0的屬性,它與您定義的x0無關。

在這種情況下,最接近你想要做的事情是getattr函數: getattr(d, x0)應該給你你想要的。

話雖如此,如果您可以避免使用它,這不是很好的做法。 我建議簡單地將du作為參數傳遞給plot2vars並在可能的情況下相應地編輯plot2vars

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM