0

In methods when is it necessary to use notation like self.variable_name? For instance, I know that in the constructor method it needs to be like

class A(object):
     def __init__(self, name):
     self.name = name

in order to give it an instance variable. However, what about in other methods? When do I need to put self in front of a variable name and when is it okay to just use a variable name?

user95420
  • 89
  • 1
  • 5

2 Answers2

1

You must always put a self as the first argument of an instance method. This is what you use to access the instance variables.

It is similar to this in other languages, but different in that it is required whereas other languages will often have instance variables in scope.

Tom Leese
  • 19,309
  • 12
  • 45
  • 70
0

Whenever you are wanting to access attributes of the particular object of type A. For example:

def get_name(self): # here, whenever this method is called, it expects 'self'.  
    return self.name

When calling this method outside of the class scope, python has self passed implicitly.

example = A('d_rez')
example.get_name()   # no arguments are passed, but self is passed implicitly to 
               # have access to all its attributes!

So to answer your question: You need to pass self whenever you define a method inside a class, and this is usually because there are some attributes involved. Otherwise, it could just be a static function defined outside the class if it doesn't pertain to a particular instance of class A.

drez90
  • 814
  • 5
  • 17