Class Members - Java vs. Python

I come from Java and learn Python. I am trying 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(hx); h.ex(); System.out.println(hx); } } 

Here 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(hx) h.ex() print(hx) 

Both programs return:

 0 7 

Here are my questions:

  • Is Python code correct?
  • The Python programming style seems to me more compact compared to Java. So I'm wondering WHY Python requires passing a "self" parameter.
  • At this point, Python seems more "complex" than Java. Or is there a way to remove the "I" parameter?
+8
java python
source share
3 answers

First, your Python code is correct.

It is just a question of how languages ​​are developed. Java uses a kind of automatic output of an object reference. Sometimes this can lead to strange behavior for non-java experts:

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

So why in java there is a this keyword that you can use (but you are not forced to) to resolve this ambiguity.

The python team decided to force the use of the word self (or any other word, but I will explain later) to avoid such a problem. You cannot get rid of it. Although java is still a more verbose language than python, and the self keyword does not affect this assumption.

However, you are not required to use the word "self" as a reference to the current object. You can use any other word that will be the first parameter of your method (but this is very bad practice).

Here you can see two links that deeply explain why "I'm here to stay":

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

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

+7
source share

So in java the structure is usually

 Class private data (aka the "struct") public data constructors (__init__ in python) functions etc 

its very similar to python. the same structure as for any functions that work with the data necessary to include itself as an argument. where java he did not have to accept arguments.

Also, it seems that in python all data is publicly accessible by default, so you do not need to use getters and setters, for example, in java.

I personally find the Python class more C-Struct with some added features, where java all throws itself into the class.

0
source share

2.) Python is a high-level language. where java is a more average level, guessing. kind of new to java.

python follows a space where java requires more formatting.

3.) the self parameter can be deleted. replace whatever you want to name.

-2
source share

All Articles