Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Members -- Java vs. Python

Tags:

java

python

I am coming from Java and learning Python, now. I try to understand the concept of class members in Python.

Here is an example program in Java:

class Hello {
    int x = 0;

    void ex() {
        x = 7;
    }

    public static void main(String args[]) {
        Hello h = new Hello();
        System.out.println(h.x);
        h.ex();
        System.out.println(h.x);
}   }

That is what I did in Python, following some examples I found:

class Hello:
   def __init__(self) :
       self.x = 0

   def ex(self):
       self.x = 7

h = Hello()
print(h.x)
h.ex()
print(h.x)

Both programs return:

0
7

Here are my questions:

  1. Is the Python Code correct?
  2. The programming style of Python appears to me to be more compact, compared to Java. So I am wondering, WHY does Python require the passing of a "self" -- Parameter.
  3. At this point Python seems to be more "complex" than Java. Or is there a way to remove the "self" -- Parameter?
like image 692
Gerhard Avatar asked Jun 02 '16 19:06

Gerhard


1 Answers

First, your python code is correct.

It's just a matter about how the languages is designed. Java uses a kind of automatic inference of a reference to the object. It can lead sometimes to strange behaviours for non-java experts:

private int a; 
public int add(int a, int b){
    return a+b; // what a will it use? 
}

So, it's why in java there's the keyword this that can be used (but you're not forced) in order to solve that ambiguity.

The python team decided to force to use the word self (or any other word but I will explain later) to avoid that kind of problem. You cannot get rid of it. Though, java is still a more verbose language than python and the keyword self doesn't affect a lot that assumption.

However you're not obliged to use the "self" word as a reference to the current object. You can use any other word that would be the first parameter of your method (but it's a very bad practice).

Here, you can see two references that explain deeply why "self is here to stay":

http://www.programiz.com/article/python-self-why

http://neopythonic.blogspot.be/2008/10/why-explicit-self-has-to-stay.html

like image 121
Alexis Clarembeau Avatar answered Oct 22 '22 23:10

Alexis Clarembeau