self parameter is used in an instance
method to gain access to the object (the instance) that called the method.
class MyClass: # The class constructor def __init__(self): self.variable = 42 # an instance method def myMethod(self): return self.variable object = MyClass() # Create an instance of MyClass object.myMethod() # Call the instance method
self as a parameter. When we instantiate an
object of type
MyClass and call
myMethod, Python will pass the
object that called the method as a paraneter to that method via the
parameter. It's like calling
object.myMethod(object) but we don't actually pass
object in. Python does it for us, and does it silently.
self means "the object that called the method", or "this" object.
This is similar to many other languages where the
this keyword is
used to access "this" object.
self is the same concept, with the difference
being that it's listed explicitely as a parameter, rather than it being an implicit
object as in other languages.
The name "self" is just a convention. The first parameter of an instance method will always be a reference to the object that called the method, and by convention we use "self". You're welcome to call it "this" or "thisObject" or whatever, but to make life easier for others it's best to stick to conventions and use "self".