Python for Java Programmers
Chapter 8: Object-oriented programming
Methods
Methods in Python are just like functions. The only main difference is that the first parameter in the method definition must take a reference to the object instance (i.e. self). This will allow you to access the properties of the instance inside the method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
Again, self basically points to the object itself (stranger in this example).
When you invoke a method, for example stranger.emigrate("uk"), Python will actually convert it to Person.emigrate(stranger, "uk") in the background. This is why there is no need to provide the first argument to self in the method call, because self refers to stranger. Obviously, you can call Person.emigrate(stranger, "uk") directly too, but let’s just keep it readable with a more conventional OOP style method call, shall we?
Explicitly using self for instance attributes and methods actually makes the code less ambiguous and more readable. In fact, you MUST explicitly use self. Remember one of Python’s design philosophy: “explicit is better than implicit”. Compare this to Java where you do not always need to use the this keyword unless it is ambiguous.