Difference between Python self and Java this

First of all, let me correct you - self is not a method. Moving further:

Technically both self and this are used for the same thing. They are used to access the variable associated with the current instance. Only difference is, you have to include self explicitly as first parameter to an instance method in Python, whereas this is not the case with Java. Moreover, the name self can be anything. It's not a keyword, as you already know. you can even change it to this, and it will work fine. But people like to use self, as it has now become a bit of a convention.

Here's a simple instance method accessing an instance variable in both Python and Java:

Python:

class Circle(object):
    def __init__(self, radius):
        # declare and initialize an instance variable
        self.radius = radius

# Create object. Notice how you are passing only a single argument.  
# The object reference is implicitly bound to `self` parameter of `__init__` method
circle1 = Circle(5);

Java:

class Circle {
    private int radius;

    public Circle(int radius) {
        this.radius = radius;
    }
}

Circle circle1 = new Circle(5);

See also:

  • Wiki page of this

About self in Python (here is the source: Python self explanation):

The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the same as functions, and leaves the actual name to use up to you (although self is the convention, and people will generally frown at you when you use something else.) self is not special to the code, it's just another object.

Python could have done something else to distinguish normal names from attributes -- special syntax like Ruby has, or requiring declarations like C++ and Java do, or perhaps something yet more different -- but it didn't. Python's all for making things explicit, making it obvious what's what, and although it doesn't do it entirely everywhere, it does do it for instance attributes. That's why assigning to an instance attribute needs to know what instance to assign to, and that's why it needs self..

About this in Java being explained by Oracle (here is the source: Java this explanation):

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.