Section 7.7 Objects and Methods
Up to this point, we have been dealing mainly with primitive data types like
int
, float
, and bool
. Most of the operations that we do on these data types is with functions. These functions are independent of the data. When we call a function, we are “telling” to the function to do things to the data.You can think of a function call like
abs(x)
as saying, “Hey, abs
, here’s a variable x
for you. Give me back its absolute value.” A call like min(4.3, 2.7)
says “Hey, min
, here are two numbers. Give me back the smaller number.”For strings, we have seen the
len
function. We can think of len("Python")
as saying, “Hey, len
, here’s a string. Tell me how many characters are in it.”When we start manipulating strings, we are going to take advantage of the fact that strings are objects. You can think of an object as a “bundle” that combines data values along with functions that can work with the data 1 . When a function is part of an object, we call it a method. The data item(s) in an object are called its attributes.
When we call methods, we turn the dialogue inside-out. Instead of telling a function to work with some data, we tell the data to use one of its methods. If the absolute value function were a method, we would say something like “Hey,
x
, give me back your absolute value.”When we work with strings, we will often use this “inside-out” way of talking to Python by using dot notation. Let’s say I have a string in a variable called
message
, and I want to have it all in upper case. I write something like this: message.upper()
, which says, “Hey, message
, give me back a string with all your letters in upper case.” The variable name comes first, followed by a dot, followed by the method name and parentheses. The “dot notation” is the way we connect the name of an object to the name of a method it can perform.Let’s take a look at the
.upper()
method and other string methods on the next page.Note to experts: Yes, I know. This is a vast over-simplification. I’m trying to motivate the discussion here, not bury people in technical details.