Python - Class Methods and self parameter

Introduction

Class Methods are function objects created by def statements nested in a class statement's body.

Class methods provide behavior for instance objects.

A method's first argument always receives the instance object that is the implied subject of the method call.

Python automatically maps instance method calls to a class's method functions as follows.

Method calls made through an instance, like this:

instance.method(args...) 

are automatically translated to class method function calls of this form:

class.method(instance, args...) 

where Python determines the class by locating the method name using the inheritance search procedure.

Both call forms are valid in Python.

Python's self argument as being similar to C++'s this pointer.

In Python, self is always explicit in your code.

Methods must always go through self to fetch or change attributes of the instance.

The presence of self makes it obvious that you are using instance attribute names in your script, not names in the local or global scope.

Example

class NextClass:                            # Define class 
    def printer(self, text):                # Define method 
        self.message = text                 # Change instance 
        print(self.message)                 # Access instance 

The name printer refers to a function object.

It's assigned in the class statement's scope and becomes a class object attribute and inherited by every instance made from the class.

Methods like printer are designed to process instances, we call them through instances:

Demo

class NextClass:                            # Define class 
    def printer(self, text):                # Define method 
        self.message = text                 # Change instance 
        print(self.message)                 # Access instance 
#  w w  w.  java2  s  .  co  m
x = NextClass()                         # Make instance 
x.printer('instance call')              # Call its method 
print( x.message )                      # Instance changed

Result

When we call the method by qualifying an instance.

printer is first located by inheritance, and then its self argument is automatically assigned the instance object (x).

The text argument gets the string passed at the call.

Python automatically passes the first argument to self for us, we only actually have to pass in one argument.

Inside printer, the name self is used to access or set per-instance data.

We can also call printer by going through the class name, provided we pass an instance to the self argument explicitly:

NextClass.printer(x, 'class call')      # Direct class call 
x.message                               # Instance changed again 

Related Topic