[Tutor] Self and class functions
Dave Angel
davea at davea.name
Sun Jun 30 03:41:38 CEST 2013
On 06/29/2013 06:36 PM, Phil wrote:
> Thank you for reading this.
You should be telling us some things. I'll guess for you:
You're using Python 3.3 with Qt for a gui, and Linux 12.04 for an OS.
>
> I'm attempting to access the GUI widgets. The buttonClicked slot does
> what I want but I'd like to access the widgets outside of the class. My
> function setLabel doesn't work because self and ui are not known.
>
> I have a second class named Frame that includes a function named dummy.
> Accessing that function is not a problem.
The function is called a method if it's actually part of a class.
You don't show us the code for that class and method. But according to
the call below, the method must be a staticmethod or equivalent.
Perhaps like the following:
class Frame:
@staticmethod
def dummy():
return 42
Static methods are strange because they have no self or cls arguments.
In other words, they're just ordinary functions which happen to be
defined inside a class. So it's in a different namespace, but has no
special arguments.
The other "strange" method is a classmethod, which takes a cls (class)
parameter instead of a self parameter.
The methods below are ordinary methods, and thus need a self parameter.
Normally that's obtained by creating an instance of the class.
>
> -------------------------------------
>
> from mainwindow import Ui_MainWindow
> from PySide import QtCore, QtGui
> from frame import Frame
>
> class DrawTest(QtGui.QMainWindow):
> def __init__(self, parent=None):
> super(DrawTest, self).__init__(parent)
>
> self.ui = Ui_MainWindow()
> self.ui.setupUi(self)
>
> def buttonClicked(self):
> print("clicked")
> self.ui.pushButton.setText("test")
> self.ui.label.setText("Testing")
>
> def setLabel(self):
> self.ui.label.setText("Bingo")
>
> DrawTest.setLabel(self)
> DrawTest.ui.label.setText("Bingo")
>
> The two lines above don't work,
You generally should specify in what way they don't work. In your case
they don't work because 'self' is unbound in top-level code. You could
use self if you were already inside a method of the same class and were
calling a different one.
> so my question is how do access the
> setText function? And, what do I do about the self parameter in the
> setLabel function?
>
Normally, you create an instance of the class. For example, you might do:
mywindow = DrawTest(parent)
Then, now you have the object, you can call the method:
mywindow.setLabel()
I have no idea about ui.label, I don't know QT.
> Accessing the Frame class is not a problem.
>
> Frame.dummy()
>
> I have spent the better part of a day searching the Internet for an
> answer and I have attempted to find an answer from two other mailing
> lists but they don't entertain low level questions.
>
You need to play with classes using a simple Python tutorial, before you
try to even understand a GUI.
--
DaveA
More information about the Tutor
mailing list