Skip to content
Advertisement

When do you use ‘self’ in Python? [duplicate]

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement