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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With