繁体   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