簡體   English   中英

如何在同一類的另一個函數中使用一個函數中的一個對象

[英]How do I use one object from one function in another function in the same class

我想在browse_file()中使用grey_scale() () 的"img" 我可以使用band_count(type Int)但是當我嘗試在grey_scale()中使用"img"時,出現以下錯誤:

the type of "img" is class 'spectral.io.bilfile.BilFile'
Traceback (most recent call last):
File "main.py", line 50, in grey_scale
view = imshow(img,(bandGrey,))`
NameError: global name 'img' is not defined`

我的代碼:

def browse_file(self,MainWindow):
    file = str(QtGui.QFileDialog.getOpenFileName(self,"Select Directory"))
    img = envi.open(file)       #load image to img object.
    band_info = str(img.read_band) 
    band_count = int((band_info.split(start))[1].split(end)[0])
    view = imshow(img,(1,0,0))

def grey_scale(self):
    bandGrey = self.spinBox_grey_band.value()
    print bandGrey      #working
    view = imshow(img,(bandGrey,))  #error 

看起來您需要將img設為實例屬性,以便它在調用browse_filegrey_scale之間“保存”在self中:

def browse_file(self,MainWindow):
    file = str(QtGui.QFileDialog.getOpenFileName(self,"Select Directory"))
    img = envi.open(file)       #load image to img object.
    band_info = str(img.read_band) 
    band_count = int((band_info.split(start))[1].split(end)[0])
    view = imshow(img,(1,0,0))
    self.img = img

def grey_scale(self):
    bandGrey = self.spinBox_grey_band.value()
    print bandGrey      #working
    view = imshow(self.img,(bandGrey,))  #error 

當然,這意味着您需要確保在調用browse_file之前調用grey_scale ,以便在使用之前定義self.img

局部變量的要點是它們只存在於函數內,所以你不能通過定義來做到這一點。

通常,答案是傳遞變量的值。 例如, browse_file可以將img返回給它的調用者,調用者可以保留它,然后稍后將它傳遞給grey_scale

另一種選擇是使用類來保存狀態。 這些函數似乎已經是一個類的方法(基於self參數),所以這很有可能是正確的設計。 只需將兩個函數中的每個img替換為self.img ,現在這不是局部變量,而是實例的成員。 在同一實例上調用的每個方法都可以訪問相同的值。 但是如果您創建同一個類的多個實例,每個實例都會有自己的img

您需要從函數browse_file()返回img

然后從該函數創建一個新變量。

接下來將 img 添加到 grey_scale() 的參數列表中

def browse_file(self,MainWindow):
    file = str(QtGui.QFileDialog.getOpenFileName(self,"Select Directory"))
    img = envi.open(file)       #load image to img object.
    band_info = str(img.read_band) 
    band_count = int((band_info.split(start))[1].split(end)[0])
    view = imshow(img,(1,0,0))
    return img

img = browse_file(self,MainWindow)

def grey_scale(self, img):
    bandGrey = self.spinBox_grey_band.value()
    print bandGrey      #working
    view = imshow(img,(bandGrey,))  #error 

grey_scale(img)

您可以在課堂上重復使用 img。

如果你想在類之外使用 img 變量,你可以將它設為全局

global img
img = browse_file(self,MainWindow)

或從類中創建一個變量。

IE。

img = class_object.browse_file(MainWindow)

暫無
暫無

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

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