0
class Grid(QFrame):

    def generate(self):

        self.pen = False
        self.tgDig = False
        self.rwDig = False

I'm not sure how this works.

The generate method is defined with self as a parameter and I understand that all methods must have a special first parameter, usually called self but I don't understand how the self invokes pen or tgDig or rwDig since they don't exist anywhere else?

It's using PyQt QFrame if that helps.

Alias
  • 415
  • 1
  • 6
  • 20

3 Answers3

0

self is refering to the object that owns the method generate, it looks like pen, tgDig, and rwDig are also members of this same class or its parent class in the case of inheritance (etc. etc.).

this might be of some use.

Community
  • 1
  • 1
RossBille
  • 1,448
  • 1
  • 17
  • 26
  • But they don't occur anywhere else, not sure how they're members of the same class. – Alias May 21 '14 at 23:15
  • After your edit it seems like the variables may exist in a parent class, or its parent class etc. etc. If thats not the case, does this cod run? – RossBille May 21 '14 at 23:30
  • Yes, the code runs, yet I can't find the declarations of the variables in those classes. – Alias May 21 '14 at 23:38
  • 1
    There's no need of a declaration, if they didn't already exist they are just created on the fly. In Python objects are in many aspects dictionaries with some syntax sugar, and you can create attributes dynamically as you would add an element to a dictionary. – Matteo Italia May 21 '14 at 23:48
0

All the methods of a class in Python have as first parameter self, which is a reference to the object itself. Like this in Java or C++. So in your example the three variables are members of the class, and you accesses it with self.

In your concrete example, you do not see the variables in the class because they are inherited from another class (QFrame). The syntax for a class to inherit from another is class MyClass(ParentClass)

Alejandro Alcalde
  • 5,990
  • 6
  • 39
  • 79
  • I don't see how they're inherited from that class as they don't exist in the class? – Alias May 21 '14 at 23:19
  • They don't exsists in QFrame? Then QFrame inherit from another class, keep looking for the parent class and you should find those variables. – Alejandro Alcalde May 21 '14 at 23:23
0

If you run the examples you will see the method resolution order and the base class that Grid inherits its attributes and methods from.

import sys
app = QApplication(sys.argv)#
from PyQt4.QtGui import QFrame,QApplication   
class Grid(QFrame):

    def generate(self):

        self.pen = False
        self.tgDig = False
        self.rwDig = False

import inspect
print inspect.getmro(Grid)
print(Grid.__bases__)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321