3

What is "self" and how can I use it error-free in a Q script?

Example:

mc = self.iface.mapCanvas()

But when I try to run this in the Console I get the following error:

NameError: name 'self' is not defined

Maybe I need to import a specific module of some kind to use 'self'?

  • 1
    substitute 'self' with 'qgis.utils' in console – Maxim Dubinin Oct 31 '15 at 1:36
  • Actually @MaximDubinin 'qgis.utils' instead of 'self' works in the script as well as in the console. But then my question remains... what is this 'self' that I see people using in scripts? It doesn't work for me. Yet. – Waterman Oct 31 '15 at 2:42
6

self refer to the instance of the class you have to load to make any QGIS plugin work e.g this example file.

In the console, you don't need the self stuff as you don't use the same loading mechanism as in a QGIS plugin.

self isn't specific to QGIS, it's a convention when doing object oriented programming with Python. You can look at some Python course to know more. This article could also help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.