简体   繁体   中英

How to use a variable declared inside a class, outside of this class?

I've got this problem with a project that involves programming in Python. I made this class with which a screen pops up and so allowing me to open a xls file. Inside this class the directory to this file is then put into this variable 'filename'. :>

class OpenFile(QtGui.QMainWindow):
  def __init__(self):
    super(OpenFile, self).__init__()
    self.initUI()

  def initUI(self):
    openFile = QtGui.QPushButton('Open Orderpakket', self)
    openFile.setGeometry(0, 00, 350, 300)
    openFile.setStatusTip('Open new File')
    self.connect(openFile, QtCore.SIGNAL('clicked()'), self.showDialog)
    self.setWindowTitle('Open Orderpakket')

  def showDialog(self):
    filename = QtGui.QFileDialog.getOpenFileName(self, 'Open file',r'J:\Integratie Project\Files', "Excel Files (*.xls*.xlsx)")

    print filename

Inside this class the variable filename indeed has the correct directory inside it. Now i want to use it here, outsite a class or a def:

wb = xlrd.open_workbook(filename)

That doesn't work, giving me the error that 'filename is not defined'

I've read about the 'global' command of Python which seems to have the solution, but i can't seem to get that working.

Anyone?

I will not get into details of your code, but will use it only to explain the basic concepts.

The variable filename in showDialog is defined as a local variable - hence, you cannot access it outside this function.

If you want to define the variable as an instance variable for the class OpenFile, you need to use self.filename .

I assume you have somewhere an instance of the class OpenFile , such as:

openfile = OpenFile()

Now you can access the variable from this instance by invoking:

openfile.filename

Add filename as an attribute to the object of your class, ie self :

self.filename = QtGui.QFileDialog.getOpenFileName(self, 'Open file',r'J:\Integratie Project\Files', "Excel Files (*.xls *.xlsx)")

This way you can access it like that:

wb = xlrd.open_workbook(openfile.filename)

where openfile is an object of OpenFile class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM