self and this
00:00
Welcome to lesson seven in Object-Oriented Programming in Python versus Java. In this lesson, we will look at Python’s use of the variable name self
and how it compares to Java’s keyword this
.
00:14
The word this
is a reserved word that is used to refer to the calling object in the body of methods so we have a way to refer to it.
00:25 This is mostly used to avoid ambiguity, typically when a parameter value has the same name as a Java field. So, for example, here’s a typical Java class.
00:42
My constructor takes parameter values for color
, model
, and year
. And because the best variable name is always the best variable name, we have used those same words for the fields.
00:55
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.
01:20
If I create a .setColor()
method because I want to paint my car and I call the parameter newColor
, I don’t need the keyword this
.
01:32
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.
01:49
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.
02:13
Python programmers have decided to use the word self
for that first parameter name. It kind of plays the same role as this
, except its use is always required.
02:29
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 color
, model
, and year
, I always precede the attribute name with the word self
in each case.
03:00
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.
03:47
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.