Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you use 'self' in Python?

Tags:

python

self

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.

like image 666
Dark Templar Avatar asked Oct 11 '11 05:10

Dark Templar


People also ask

When would you use self in a method?

You use self when: 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. Referencing a class or instance attribute from inside an instance method.

Should you always use self python?

Self is a convention and not a Python keyword . self is parameter in Instance Method and user can use another parameter name in place of it. But it is advisable to use self because it increases the readability of code, and it is also a good programming practice.


2 Answers

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... 
like image 35
Oskarbi Avatar answered Oct 07 '22 17:10

Oskarbi


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.

like image 154
agf Avatar answered Oct 07 '22 18:10

agf