38

Are you supposed to use self when referencing a member function in Python (within the same module)?

More generally, I was wondering when it is required to use self, not just for methods but for variables as well.

agf
  • 171,228
  • 44
  • 289
  • 238
Dark Templar
  • 1,129
  • 3
  • 11
  • 18

4 Answers4

50

Adding an answer because Oskarbi's isn't explicit.

You use self when:

  1. Defining an instance method. It is passed automatically as the first parameter when you call a method on an instance, and it is the instance on which the method was called.
  2. Referencing a class or instance attribute from inside an instance method. Use it when you want to call a method or access a name (variable) on the instance the method was called on, from inside that method.

You don't use self when

  1. You call an instance method normally. Using Oskarbi's example, if you do instance = MyClass(), you call MyClass.my_method as instance.my_method(some_var) not as instance.my_method(self, some_var).
  2. You reference a class attribute from outside an instance method but inside the class definition.
  3. You're inside a staticmethod.

These don'ts are just examples of when not to use self. The dos are when you should use it.

chris Frisina
  • 19,086
  • 22
  • 87
  • 167
agf
  • 171,228
  • 44
  • 289
  • 238
17

Use self to refer to instance variables and methods from other instance methods. Also put self as the first parameter in the definition of instance methods.

An example:

class MyClass(object):

    my_var = None

    def my_method(self, my_var):
         self.my_var = my_var
         self.my_other_method()

    def my_other_method(self):
         # do something...
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Oskarbi
  • 297
  • 1
  • 8
  • So "class MyClass(object)" is a constructor? I see that 'object' is a parameter but not sure what that means... – Dark Templar Oct 11 '11 at 06:16
  • @DarkTemplar Parameters in a class definition are base classes (there is also a keyword parameter, `metaclass` for setting the type of the class in Python 3) – agf Oct 11 '11 at 06:43
  • 2
    That's not a constructor, but the class defintion. As @agf says, `object` is just the base class. When you instantiate the class you don't have to pass any parameter (except if you have specified a `__init__(self)` method with more parameters). – Oskarbi Oct 11 '11 at 10:48
  • 1
    having my_var as an attribute and not as self.my_var, may lead to malpractice as it serves as a static attribute. all instances of the class will share that same variable – msarafzadeh Jan 30 '20 at 14:27
6
  1. There is nothing 'special' about the name self. It is the name preferred by convention by Pythonistas, to indicate what that parameter is expected to contain.

  2. The Python runtime will pass a 'self' value when you call an instance method on an instance, whether you deliberately provide for it or not. This will usually result in an easily diagnosed/understood error (since the function will get called with the wrong number of parameters), but the use of *args can lead to rather more strange type errors.

  3. The parameter is passed implicitly when you call an instance method on an instance. It contains the instance upon which you call the method. So you don't mention self in the function call because (a) as noted above, that wouldn't make any sense (there isn't a self in scope, in general, and self is not a keyword or special name or anything); (b) you've already indicated the instance to use (by writing my_instance.).

  4. You can, of course, explicitly call an instance method by accessing it from the class. In this case, you'll need to pass the instance explicitly as the first parameter. You generally speaking don't want to do this. And you especially don't want to write code that considers the possibility that the first parameter is something else that's been explicitly passed in this way. This is akin to checking if (this == null) in C++: you don't do it, because if it could possibly mean anything, then the calling code is wrong, morally if not legally. (At least in Python you won't have problems with undefined behaviour, but it's still morally wrong.)

  5. Within the instance method, since self is a parameter which has been assigned the instance as a value, you can write self.whatever to access attributes of the instance. Unlike in some other 'implicit this' style languages, the attribute names are not implicitly "in scope".

  6. There are no other use cases for self, since again it's not a special name, and that is the one specific purpose that the naming convention addresses. If you needed to access a 'variable' (really an attribute) from another module, you would use the module name. If you wanted to access one from the current module, no prefix is needed, or really possible for that matter. (Well, you could explicitly look it up in the dict returned by globals(), but please don't do that.)

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
3

For instance variable and for methods it is mandatory to use self anytime.

lc2817
  • 3,722
  • 16
  • 40
  • So when in doubt, always go with it? – Dark Templar Oct 11 '11 at 06:06
  • 1
    @DarkTemplar You always use self when _defining_ an instance method, or calling one or referencing an instance variable from inside an instance method -- not otherwise. I don't know what he intended with "anytime" but it's not true as taken literally. – agf Oct 11 '11 at 06:41
  • 1
    That is exactly what I meant by anytime. Anytime you could use this in Java for example you have to use self in python. @afg Thank you for precising it. – lc2817 Oct 11 '11 at 08:19
  • 1
    Well, except that `self` isn't a Python keyword and you can call the first parameter passed to a bound instance method anything you want if you don't mind defying convention and annoying anyone who reads your code. – Wooble Oct 11 '11 at 11:25
  • 2
    You are right Wooble. From the official pydoc: _Often, the first argument of a method is called self. This is nothing more than a convention: the name self has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers, and it is also conceivable that a class browser program might be written that relies upon such a convention._ at http://docs.python.org/tutorial/classes.html – lc2817 Oct 11 '11 at 14:19