I had done a bit of Python long back. I am however moving over to Java now. I wanted to know if there were any differences between the Python "self" method and Java "this".
I know that "self" is not a keyword while "this" is. And that is pretty much what I could figure out. Am I missing anything else?
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: