self and this
So, to identify that I’m assigning values to the fields, on the left-hand of the assignment statements in the constructor, I precede each variable name with the word
this. That way, Java knows that you’re referring to the field
.color when you say
this.color and not the parameter name
color. Its use isn’t necessary.
I could put it in if I wanted, but it’s not necessary. There’s no ambiguity.
color refers to the field—there’s no other word
color in the scope of this method.
newColor is a different name, so that works.
Python similarly uses the word
self. When writing a method in Python, every method must have at least one parameter, and that parameter is the name you’re going to use to refer to the calling object, and that’s what Python uses to refer to the calling object.
If I take a look at a similar Python class, notice every method that you have seen so far has that first parameter
self, and that’s the name we’re going to use to refer to the calling object in any method that we write. So, in the initializer, when I provide additional parameters for
year, I always precede the attribute name with the word
self in each case.
If I want to create a
.setColor() method in the Python version of this class—again, to repaint the car—even if I call the parameter
newColor, I still have to use the word
self as the first parameter for this method because I still have to use the word
self to precede the attribute name. So, unlike Java’s keyword
this, the use of the word
self is actually required and we provide that name as the first parameter to any method that we write in this class, even if it is the only parameter for that method in that class.
So, that is how we use the word
self in writing methods inside of a class. In your next lesson, we’ll take a look at the concept of a Python function and how it’s separate from a class or object’s method.
Become a Member to join the conversation.