Using Objects (part 1)
Back when we talked about data types, we talked about them as if they were pretty similar in how they acted.
When we learned about built-in functions, we learned that strings interact differently with functions than ints, floats, and booleans do.
When we learned about lists, we learned that they interact similary with functions to strings.
What has been going on here is that strings and lists are both what we call objects.
Types like int
, float
, and boolean
are what we call “primitive” (basically not an object).
An object has state and behavior.
For example, a string’s state would be the letters that it stores and its behavior is the functions that you can call on it.
s = "hello" # state: "hello"
print(s.upper()) # behavior: can give you the upper case version
print(s.islower()) # behavior: can tell you if it is lower case
state: corresponds to the underlying data
behavior: corresponds to functions that you can call on an object
Identifying Objects
An object in python is anything that we will interact with by calling functions following the syntax:
return_value = value.function(parameters) # value is an object
# as opposed to
return_value = function(value) # value is not an object
Here are some examples with strings and lists. You should have a sense for how to go about using objects. We’ll dive into what exactly an object represents in the future.
k = ["dog", "cat", "parrot"]
num = k.count("dog") # lists are objects
s = " ".join(k) # strings are objects