Difference between Python self and Java this

后端 未结 4 1031
暗喜
暗喜 2020-12-23 16:04

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

4条回答
  •  心在旅途
    2020-12-23 16:25

    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.

提交回复
热议问题