0

Do I always need to use 'self' when creating a variable? I'm finding that there are actually a lot of times when when I'm creating variables and would prefer to not use the self argument.

A super simple example of this is below. (Scripting in Autodesk Maya) I've created a method that creates a group, assigns the name of it to variable groupName (this is just because if two objects have the same name it automatically adds a number on the end) and then returns that variable.

def createGroup(self):
    cmds.group(name = "FBX_Export_Group", em = True)
    groupName = cmds.ls(sl = True)[0]

    return groupName

Then, back in the __init__ method, I've got the following line,

self.exportGroup = self.createGroup()

which is both calling the method and assigning the returned variable to one that can be used class wide. This is just a simple example. One note that may be important is that currently there is only one instance of this class being created each time the script runs.

I really like this way of working because I find it easier to keep track of all my variables this way, as well as identifying which variables are being used only in one method and which ones are being used throughout the script. It also means less typing overall.

At the moment, the code works exactly the same as if I was working with self.groupName (or any variable). What I'm wondering is, is there any specific reason why I should always use the self argument? Will not using self before a variable cause problems when I start using more than one instance of the class? Is it just good practice? All the tutorials I've seen so far seem to do it that way but I don't get why it needs to be done that way.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 3
    No, you only need to use `self` if you want to modify a property of the current object. There are a ton of other things you can do in Python besides modifying object properties... so again: no. – deceze Mar 07 '16 at 12:33
  • 3
    You stroke a `self.cat` and this particular cat purrs. You stroke a `cat` and all cats of the world purr. – Psytho Mar 07 '16 at 12:34
  • 2
    @Alex Or perhaps just your local cat, depends... – deceze Mar 07 '16 at 12:36
  • Think of `self` as what `this` is to C++/Java. A variable defined within the constructor or a method without `self` will have local scope, with `self` it becomes a member of the class. If this make no sense then probably you need to refresh the fundamentals of object oriented programming. – John Smith Mar 07 '16 at 12:52
  • @Alex.S It can either be all cats of the world purr as you point out or just your local temporary imaginary cat as @deceze points out, depending on where `cat` is defined. – John Smith Mar 07 '16 at 12:54

0 Answers0