[英]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.