In this lesson we're going to combine our knowledge of functions with a new topic - objects. 1
Objects are the basis for every Python program that you will ever write. 2
Not to oversimplify, but when programming in Python we do things with stuff. 3
Please pardon my formality. 4
By 5
"do things" 6
I mean calling functions - functions that add two numbers, functions that import data, functions that fit 7
regressions or generate charts or train machine learning models. And by "stuff" I mean objects. 8
This lesson will be all about the stuff part. 9
So let's talk about objects. You see, 10
pretty much everything in Python is an object. 11
Remember those modules that we talked about in previous lessons - modules like pandas, math or our own 12
life module? 13
Those are objects. 14
We also had data frames that we put inside our X and y variables. Data frames are objects too. 15
And the plot inside our plt variable is also an object. More formally, all the data in Python 16
take the form of objects and the goal of this lesson is to explain the code that we wrote in previous 17
lessons in more detail. By the end of this lesson, 18
I want you guys to have a deeper understanding of how 19
pd.read_csv and plt.show and regr.intercept actually work. 20
My goal is to make these lines of code make a lot more sense. 21
Let's make a real life analogy to objects in Python. 22
Now suppose you have a car. 23
If you don't own a car, don't worry. 24
Owning a car is not a prerequisite for this course. 25
Actually, I don't own a car myself but I've watched enough Top Gear to get very good at talking about cars 26
and pretending I own one. 27
Anyhow, we're going to talk about your red car like it's a Python object. 28
First off, your car needs to have a name. 29
After all, every decent car has a name. 30
David Hasselhoff's car in Knight Rider was called Kit and in Pixar's movie, the protagonist was called 31
Lightning McQueen. 32
So in honor of Pixar we're gonna name your red racecar 33
"lightning_mcqueen" all lowercase and with an underscore to keep with Python naming conventions and also 34
avoid expensive American lawsuits. 35
Now if you have to describe this car to your friends, you might talk about your car's color, 36
the number of seats it has, the power of the engine or how much petrol you have left in the tank. 37
All these things are attributes of your car. 38
Now there's something quite significant about this - namely these attributes capture information about 39
the state of your car and your car's state can change. 40
For example, as you're driving along, the amount of fuel in the tank will decrease. In the same way, 41
if you've got a computer game the state of the game will also change, right? 42
Most obviouslym the level that the player is on will change as the program runs. 43
This is the kind of thing I'm alluding to when I'm talking about state. But coming back to these attributes, 44
let's talk about these attributes in a bit more detail and look at the Python's syntax. 45
The thing is much of Python programming boils down to this simple pattern "object.attribute". 46
So if you were writing a piece of Python code, accessing the attributes of your car then you might write 47
something like "lightning_mcqueen.color" or "lightning_mcqueen.engine_power" or "lightning_mcqueen 48
.mileage". 49
We've actually encountered this object.attribute pattern many times before. 50
One of the best examples is when we pulled out the coefficient of our regression or when we accessed the intercept 51
of the regression. In both of these cases, the linear regression inside our regr variable was the object - 52
and this object had an attribute called "intercept_". 53
Now don't worry about the underscore at the end of this name. 54
It's just part of the name of the attribute. 55
The underscore has no special meaning - they could have called his attributes something else but they 56
tagged on the underscore at the end of the name. 57
The point is that we also used the same "object 58
.attribute" pattern when we were talking about our Python modules; with "hitchhikersGuide 59
.theAnswer" and "math.pi". In all of these cases we were able to access information from inside our 60
object using the dot notation and it didn't matter if that object was a linear regression or if it was 61
a Python module. 62
Now accessing information from objects through their attributes is very well and good but remember how 63
we said that Python is all about doing things with stuff. 64
This is where our functions come in. However, because we really like computer programming jargon, 65
we're gonna use a different word to refer to functions in this context. Functions that are used with 66
an object are called methods. 67
Now oftentimes you'll hear the word function and method used interchangeably 68
and trust me I'd be the last person to nitpick about this use of language but it's still a good idea 69
to get familiar with all this vocabulary because you'll definitely come across these words online and 70
also nobody enjoys getting corrected by strangers on the Internet in online forums. 71
So use methods when you're talking about functions that belong to an object. 72
Let's return to our car example. Before we talked about how our car has a state. 73
It can be a new car with low mileage; it can be an old car with high mileage; the car's fuel tank can 74
be full or the car can be almost out of petrol. 75
The state of the car object is captured through the attributes of the car. 76
An attribute is a piece of information about the car like the mileage or the amount of fuel. 77
Now, unless you're playing Top Trumps, the most interesting thing about a car is not its stats but what 78
the car does. 79
And the coolest part of the car is definitely its behavior. 80
Remember that we said programming is about doing things? Well, things get done by calling methods and 81
methods are the name for functions that belong to an object. 82
So, an example of a method on our car object would be something like drive(). 83
Now the question is, how do we call one of these functions that's associated with our car? 84
Well, the format is exactly the same as with the attributes - we use the dot notation. 85
In other words, we have our object, then a dot and then name of the method. 86
So for example, if your red race car can drive then we'd write "lightning_mcqueen.drive()", and if 87
your car can do other things like talk, then we'd follow the same pattern. 88
That's enough theory. 89
Let's put this into practice and add a function to our 90
life.py file. So open the life.py file from your project's folder. In here, 91
we're going to create a function by using the keyword def and we're going to call this function 92
"quote_marvin". 93
A function is not going to take any arguments so we'll just put empty parentheses and then a 94
colon and inside the function, we'll put a print statement. 95
We're gonna print out a single sentence, so we'll have two single quotes and then we'll write. 96
"Ive calculated your chance of survival, 97
but I don't think 98
you'll like it". 99
Now check out what happens if we add an apostrophe before the t 100
in "don't". Putting that single quote there terminates our string, so anything after the single quote is 101
considered to be 102
Python code and then we have another single quote here. 103
So this is a problem, right? 104
We've got a special character, that single quote, inside of our piece of text. 105
The obvious problem is that in Python single quotes also go at the beginning and at the end of a string 106
to tell Python that something is a piece of text. 107
So, we need to tell Python that it should ignore the single quote in don't. 108
In other words, we have to escape the single quote character. To escape a special character like this 109
we have to add a backslash in front of it. 110
This is what a backslash looks like. 111
Notice how as soon as I put it there the syntax highlighting changes, this single quote is ignored 112
and now this single quote at the end is what terminates this string. 113
Now if you're looking at your keyboard you don't want to use this one here. 114
This is the forward slash. 115
And this does not escape the single quote. 116
You want to use the backslash. 117
I am going to add two more backslash us in single quotes. 118
I might add one here, and I'm going to add one here. 119
Now let's save the file and then return to the Python intro notebook that we've been working in. 120
We go to File > Save. I'm going to switch tabs to the Python intro notebook, 121
and this is where we've imported life as hitchhikersGuide. 122
Now if you returning to this notebook and have not run the code in here for a while, you can either click 123
inside this cell here and press Shift+Enter on your keyboard to rerun the cell or you can go to "Cell" 124
and then "Run All" to run all the cells in the notebook. 125
After you've done that go to the bottom of your notebook and there as a challenge see if you can call 126
the quote_marvin method. 127
If you call this method successfully, then you should see a quote from the Hitchhiker's Guide To The Galaxy 128
appear below the cell after you run it. 129
I'll give you a few seconds to pause the video. 130
And here's the solution. 131
You'd write "hitchhikersGuide.quote_ 132
marvin()" and hit Shift+Enter. 133
Remember, to call the quote_marvin method, 134
we need to use our module object. 135
In this case, our module has the name hitchhikersGuide. 136
Put a dot after hitchhikersGuide and then write the method name. 137
Now, suppose you just tried to run quote_marvin on its own, without the object. 138
In that case you'd get an error. 139
The error would read "name 'quote_marvin' is not defined". 140
In other words, our Python notebook doesn't recognize a function called quote_marvin and this is because 141
quote_marvin belongs to the life.py file. 142
It belongs to the module, not our Python intro notebook; and this neatly illustrates the difference between 143
a function and a method. To use quote_marvin, 144
we need to have that object and use the dot notation. In contrast, for a function like print or for a 145
function like type, 146
we didn't have to have anything before that function name. Print and type are functions, while quote_marvin 147
is a method. 148
So let's revisit our old notebook with the linear regression again. Looking at this code, 149
pd.read_csv 150
we now see pd as the object and read_csv as the method. 151
And below, 152
we can now recognize plt as the object and scatter as the method. 153
In fact, we're calling a whole host of methods on this plt object, including xlabel, ylabel, title 154
and show. 155
Now a question that we get a lot and something that can be a little bit confusing is the link between 156
variables and objects. 157
So let's talk about this a little bit and link how this lesson ties in with what we said about variables. 158
Back at the top of our Python intro notebook, 159
we had a variable called myAge. 160
The question you might ask at this point is "Is myAge an object?" and the way to think about it is this - 161
variables are containers. Variables are boxes that hold on to data. 162
The thing inside the variable is the actual object. In this case, 163
the object is the number 32. The object is the data and the variable is the name that is referencing 164
the number 32. Looking at the linear regression notebook, 165
we had a variable called capital X. X contained our movie budgets as a data frame. 166
The data frame contained inside of X is the object. And X is just the name for the data frame. 167
So in summary, a variable is a way to refer to an object at some point in time. 168
Variables are containers for data, but a variable is not the data itself. And this is actually quite important, 169
because it links back to our lesson on data types. You see, in Python the type actually lives with the 170
object and not with the variable. 171
Check this out. 172
When I scroll to the bottom here and in this cell right here I'm going to write 173
myAge = '200' and then I'm going to write type(myAge) and hit Shift+Enter. 174
This now shows me that myAge is a string at this point in time of the program. At the top of the Python 175
notebook, 176
myAge was still an integer - an int, but at the bottom of this notebook myAge is now a string. 177
In other words, I can change the type of myAge so let's change it again, I'm going to say "myAge = 178
20.53", then I say type(myAge) and hit Shift+Enter. 179
Now we see that myAge is a float so in our notebook myAge starts out as an integer equal to 32. 180
Then it becomes a string and then it becomes a floating point number. Now this piece of code will actually 181
really, really freak out a Java or C programmer, by the way. The Java and C guys watching this probably 182
just had a cold shiver run down their spine like when they watched the girl come out of the well in 183
the horror movie The Ring. 184
The important point I'm trying to make here is that in Python that type lives with the object inside 185
the variable, not the variable itself. 186
So in this code we've simply changed what the object is inside of my age, inside of the variable; we've 187
changed which object the variable is referencing. And there's actually another important link to our 188
lesson on types - namely the fact that the behavior of the object will depend on its type. 189
So our car can drive because it's of type car. 190
And we could add one to myAge because it was a number. 191
In other words the operations that you can do on an object depend on its type. 192
So even your simple integer is an object in Python an integer has a value say like 199, and then some 193
operations that we can do on it like multiplying or adding. 194
And this is why programmers like to think of objects as pieces of computer memory with a value and a 195
set of operations. In Python we actually care more about what an object does rather than what it is. 196
Python programmers care more about an object's behavior and its methods than what its data type is. 197
This is what makes Python's types dynamic and this is at the root of Python's flexibility 198
as a programming language. On pythons Wikipedia page, 199
this is what people mean when they talk about Python's dynamic type system. That said, I harp on and on about 200
types because, in my experience, even though they give Python a lot of flexibility they're also a big 201
stumbling block 202
when you first starting out with Python. Now, as a challenge, let's put a couple of the past lessons together. 203
You're back as the engineering lead at the calculator company in Silicon Valley. 204
You've been laughing at your boss's terrible jokes and you've got a big bonus, but your company needs 205
to ship its calculators to its first paying customers ASAP. 206
So it's crunch time for you and your development team, and it's on you to implement the square root functionality 207
of the calculator. 208
Here's what you got to do. 209
You got to open that life.py file and you've got to import the math module and then you're 210
going to try to figure out how to use the python square root functionality from the math module. You're 211
going to create your own function called square_root, 212
and that function is going to take one input and return the square root of whatever that function has 213
been given as an argument. After you're all done, 214
you're going to save the life.py file and in your Jupyter notebook, you're gonna go to Restart and 215
Run All. Finally in the bottom cell of your python intro notebook, 216
you can calculate the square root of 63.14. I'll give you a few seconds to pause the 217
video and have a go at this challenge. Ready? 218
Here's the solution. At the top of our life.py file, we're gonna import math 219
and then we're gonna create a function called def square_root and it's gonna take a single 220
input, say x, semicolon and then in the body of the function we're going to return the result of the calculation. 221
So the question is how do we make that calculation? The way we figure this out is that we're going to 222
Google for the official Python documentation on the math module. 223
So we're going to write Python math module documentation into Google and then we're gonna go to the 224
Python 3, which is what we're using, 225
documentation. The documentation will look something like, this and it's a pretty long page, but let's 226
see if we can find square root and if we search for the words square on this page we can see that the 227
guidance for using the square root in the math module looks like this. 228
We'd have to use the math module then put a dot after it and then write sqrt and provide a single 229
argument. Let's use this functionality back in our life.py module. On the same line where we have 230
our return statement, 231
we're going to write math.sqrt, and we're going to provide the same input, the same parameter 232
that we have for our function. 233
So the name of that parameter in our case is x. 234
Now again the exact name of this parameter doesn't really matter. 235
We could've called this thing something else. 236
In this case we'd have to be consistent. 237
We'd have to call this something else as well. 238
That way we're using the same parameter. Back in our Jupyter notebook, 239
we said we'd go to Kernel > Restart & Run All to make sure that this works no matter what it is that 240
you've been doing prior to getting to this point in the video. 241
So here in our last cell we can write hitchhikersGuide.square_root, and then provide 242
the value 63.14. 243
This was the last part of the challenge. Hitting Shift+Enter, 244
I can see an attribute error. 245
Life has no attribute called square root. 246
What did we forget to do? 247
If you're getting this as well, it's because you haven't saved your life.py 248
file and you can actually tell that they are unsafe changes by the little star in the name 249
of the tab. 250
So go to file, hit Save, that little star will disappear and it'll say that your file was saved a few 251
seconds ago. And back in our Python notebook, 252
we're gonna have to go again to Kernel > Restart & Run All. 253
Scrolling down now we can see that our cell has evaluated correctly. 254
And the square root of 63.14 is about 7.95. 255
So there you go. 256
We've got the solution right below our cell, but since our method here is returning a value, let's save 257
this value in a variable. 258
So when I say "result = hitchhikersGuide.square_root". And then below I am just going to print 259
the result and hit Shift+Enter. So I hope this lesson helped demystify the code that we've written previously 260
and explain what's going on behind the scenes. 261
Looking at this line of code, reading "result = hitchhikersGuide.square_root(63 262
.14)" 263
We can see that it's exactly the same pattern as with the Python code that we wrote when we're doing 264
our linear regression. 265
There we wrote 266
data = pd.read_csv 267
We've got an object called pd. 268
It has a method called read_csv 269
And that method is returning a value that we're storing in a variable called theta. 270
Cool. 271
So at this point you pretty much know Python. 272
So now Ryan Sawyer's comic here can probably bring a smile to your face as well. 273
Also, I bet you're itching to use your Python knowledge to run another regression. 274
I'm gonna head off and grab a bite to eat now, but I do look forward to seeing you in the next lesson. 275
Take care.