96

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?

2
  • 2
    What do you mean by "self method"? Commented Feb 11, 2014 at 6:45
  • You also don't have to have self (or in Java's case, this) as the first parameter of a class method in Java. Commented Feb 11, 2014 at 6:51

4 Answers 4

139

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:

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks, much more helpful than the copy/pasted accepted answer, IMHO
Thanks - very helpful answer as it compares the two side by side.
Concise and on point. Thank you! Better than the chosen answer
Be aware of the difference in case of in inheritance and overriding as mentioned by @林果皞. If you have a parent-child class hierarchy, in Java this in parent refers to parent, but in python self in parent refers to the child.
@zardosht: That is not the case. this in Java and self in Python both refer to the instance. There are no separate parent and child objects. Java is statically typed, so this in the parent will have a static type corresponding to the parent, but this doesn't affect what actual object it refers to.
|
45

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.

Comments

17

Be careful super can keep its own version of this.i in Java, but self.i always refer to the child in Python.

Main.java:

class Parent {

    int i;
    Parent() {
        this.i = 5;
    }

    void doStuff() {
        System.out.println(this.i);
    }
}

class Child extends Parent {
    int i;
    Child() {
        this.i = 7;
    }
}

class Main {

    public static void main(String[] args) {
        Child m = new Child();
        System.out.println(m.i); //print 7
        m.doStuff(); //print 5
    }
}

Main.py:

class Parent(object):
    i = 5;
    def __init__(self):
        self.i = 5

    def doStuff(self):
        print(self.i)

class Child(Parent, object):

    def __init__(self):
        super(Child, self).__init__()
        self.i = 7

class Main():

    def main(self):
        m = Child()
        print(m.i) #print 7
        m.doStuff() #print 7

m = Main()
m.main()

Output:

$ java Main 
7
5
$ python Main.py 
7
7

[Update]

The reason is because Java's int i declaration in Child class makes the i become class scope variable, while no such variable shadowing in Python subclassing. If you remove int i in Child class of Java, it will print 7 and 7 too.

3 Comments

The practical advice though, is to not use the same variable name in both child and parent, and that is true for both languages.
Then, how can I make a private member variable/property to be not overriable by subclass? To avoid internal states be exposed in python?
@Lenik Python does not support true private variables; techniques like name mangling, property, and CPython extensions only enhance privacy.
1

From my perspective, the most obvious difference is that in java class, in the constructor, you need to specify the field

this.radius = radius

While in the python code, you don't have to do so, it's implicit.

1 Comment

Don't you have to do that in python too? If you want to refer to radius with self then you need to give it the attribute

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.