Classes#
Q&A
Q: will we learn any methods for tuples? A: No…they exist…although there are only two (see here) But, we don’t use tuples a ton so I don’t focus on them/
Q: will quotations be included as a space?
A: Nope. A space will only be included if there is a space between the quotes
Q: why did question 2 print out the final correct list option 3, but when in the example in class when we did the upper of hello example when the last print statement is there it went back to origonal.
A: List methods operate in place. String methods operate not in place.
Q: In A3: when you’re working with None, why can’t you set a variable equal to None (something like “a = None”)
A: You can set a variable equal to None!
Q: Also, why does the identity operator “is” work when you’re checking if something equals None, but “==“ doesn’t?
A:==
does work. For example, the following returns True:
a = None
a == None
Q: I’m very confused about when to know to use range(len()) and when to use append vs += and how to know the appropriate way to get the output of loops
A: If you want to loop over 1 through however many things there are in a list (for example), you’d use range(len()). Append is when you want to add something to the end of a list += is for when you want to extend a string or add a number to a numeric variable. As for how to get output of loops - this is a great question for office hours!
Q: as mentioned previous that instead of using 200, we have to use key, since key=200, what if we don’t not use that
A: Then you’ll only be able to use 200 within the function; no ability to use a different value
Q: are the brackets necesary
A: Brackets are necessary any time you want to indicate we’re looking at a list
Q: Still confused on the try/except. How is it not just one code block running like conditionals?
A: It’s the way it works. For a try/except, python will always try the code in the try block first. If that code executes without error, it’s done. If, however, an error is raised, it will execute the code in theexcept
instead.
Q: just to clarify attributes store information, and methods are functions?
A: Yup! We’ll deepen this knowledge today!
Announcements
Due this week:
CL5 due Friday 5/9/25
mid-course survey (“due” for EC Friday)
Notes:
E1 will be viewable on PrairieLearn tomorrow (Fri) afternoon
Next week there will be one VQ (due Mon); none for Wed
A4 due next Sun
The withdrawal deadline is end of this week
Class is out of 100 points; 51 pts remain
Need 70 pts to pass the course
Classes Overview#
Objects
Classes
Attributes
Methods
Instances
__init__
What is an Object?#
Python is an object oriented programming language. This is the definition that most web browsers and search engines give you, but what does it mean?
An object is a specific example created from an instance of a class. Since Python is a object oriented, that means everything you have been working with has been a form of an object.
So what is a way of thinking about Classes and Objects?
Objects and Classes can be compared to like how a type of number can be defined as an integer int
or float float
in Python
x = 5
y = 20.25
type(x)
int
type(y)
float
What is a Class?#
A class is a blueprint for creating objects
How do we create a Class?#
We use the keyword class
in order to make classes in Python
Understanding Class Attributes#
Think of a classes as a blueprint for creating objects. Let’s use a real world example: a Human.
Class Attributes#
Class attributes are like variable assignment or characteristics that ALL humans share. For example:
All humans have two legs
All humans are two eyes
All humans have one hair color
It’s like saying “every human has these things in common!”
But instead of making a human, let’s make a Class of something else…
Something a little more realistic and uses the concepts we have learned in the previous weeks!
Like Spotify!
So let’s create our first class Spotify
and add platform_name
as an attribute
assign it to the str
Spotify
.
Remember Variable Assignment!
Initially look like this:
class Spotify:
pass
# creates a class Spotify
# with a single *class* attribute platform_name
class Spotify:
platform_name = 'Spotify'
How do we use a class?#
We need to make an instance of the class
An example of a Class Instance for a Human
Class is:
class Human:
number_of_legs = 2
myhuman = Human()
Now let’s make it but for our Spotify Class!#
Make an instance of Spotify and assign it to variable called my_music
# my_music is an *instance* of the Spotify object
my_music = Spotify()
How do we check the value of a class attribute?#
We put a period after instance’s name and type out the class attribute’s name platform_name
Here’s an example of using it with the Human
Class.
myhuman.number_of_legs
2
Hint: Tab is your best friend!
Let’s check the value for the class attribute platform_name
in our Spotify
Class.
my_music.platform_name
'Spotify'
Exercise: Adding more Class Attributes#
Add a class attribute called
playlist
and make it a empty listAdd a another class attribute called
total_playlists
and assign it 0Run the newly added class attributes
Caution: You may run into an error if you do not reupdate both our class Spotify
and our instance my_music
because updating one of them is not enough
# Spotify object now has thre class attributes
# these will be the same for every Spotify-type object
class Spotify:
platform_name = 'Spotify'
playlist = []
total_playlists = 0
my_music = Spotify()
my_music.playlist
[]
my_music.platform_name
'Spotify'
my_music.playlist
[]
my_music.total_playlists
0
Activity: Classes 1 Google Form:#
https://forms.gle/pcpJCwN8Y8eKszEU7#
class Circle():
pi = 3.14
degrees = 360
my_circle = Circle()
my_circle.degrees
360
Now that we know how to make a Class Attribute, let’s learn how to make a Class Method!#
Class Methods#
Class Methods are like actions that a Human can do. For example:
A human can walk
A human can talk
A human can read
Think of class methods as functions or “actions a Human can do.”
But what actions can Spotify do?
Another way we can think of actions are features for an App or in this case: Spotify.
What are some important features that Spotify provides?
Some might say downloadable playlists, Spotify Wrapped, podcast, and etc.
In general, one of the staples to a Music App is being able to have a Liked Playlist or Favorite Playlist.
First, let’s make a dictionary called songs
where the keys are the artist’s name as a str
and the values as a list
of their songs
songs_by_artist = {'Brandi Carlile' : ['The Mother', 'The Story', 'Right on Time'],
'The Beatles' : ['Hey Jude', 'Abbey Road']}
Then make a class method favorite_songs
that allows us to add our favorite songs!
It takes an input songs_by_artist
is a dictionary where we will put our songs where the key is the artist’s name and our values is a list of songs.
We want our method favorite_songs
to take in a dict
and return an embedded list, a list in a list, of the songs.
We want our output to look like this:
[['intentions', 'starfall'],
['talk to me', 'starfall'],
['Reality', 'yayyoung'],
['If You Only Knew', 'yayyoung']]
Our code should initially look like this:
class Spotify:
platform_name = 'Spotify'
playlist = []
total_playlists = 0
def favorite_songs(self, songs_by_artists):
Hint: Use psuedo code or notes using #
to break down complicated things!
# recalling songs dictionary I defined earlier
songs
{'Brandi Carlile': ['The Mother', 'The Story', 'Right on Time'],
'The Beatles': ['Hey Jude', 'Abbey Road']}
class Spotify:
platform_name = 'Spotify'
playlist = []
total_playlists = 0
# this is a class method
# it's a function defined *inside* of a class
def favorite_songs(self, songs_by_artists):
output_list = []
# looping over the keys and values in the input dictionary songs_by_artists
for artist, lst_songs in songs_by_artists.items():
# loops over each of the songs in the list (which is the values of the input dictionary)
for song in lst_songs:
# add song and artist for each song in the input dictionary
output_list.append([song, artist])
return output_list
# create an instance of my updated Spotify object
my_music = Spotify()
# add my favorite songs using the favorite_songs method
my_music.favorite_songs(songs_by_artists=songs)
[['The Mother', 'Brandi Carlile'],
['The Story', 'Brandi Carlile'],
['Right on Time', 'Brandi Carlile'],
['Hey Jude', 'The Beatles'],
['Abbey Road', 'The Beatles']]
# class attributes still exist
my_music.playlist
[]
Caution!#
What happens if I do not put self
in my Class Methods?
class Spotify2:
platform_name = "Spotify"
playlists = []
total_playlists = 0
# !!!! self is missing as the first parameter here !!!!
def favorite_songs(songs_by_artist):
lst = []
for artist, songs in songs_by_artist.items():
for song in songs:
lst.append([song, artist])
return lst
my_music2 = Spotify2()
my_music2.favorite_songs(songs)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[23], line 1
----> 1 my_music2.favorite_songs(songs)
TypeError: Spotify2.favorite_songs() takes 1 positional argument but 2 were given
So why does this happen?
This is because of when you define a method inside a class, the first parameter is always the object itself, which is called self
.
Self
allows any class method to access and use the instance attributes you have previously defined and other class methods within your Class
.
You can think of this as the class methods as operating on itSELF.
Just remember to put self
in all of your Class Methods!
But what is an Instance Attribute?
Course Announcements
Due this week:
VQ11 due Wed
CL6 due Fri
A4 due Sun
Notes:
Thanks to all who completed the mid-course survey! (N=501/610; 82%); EC has been posted to Canvas
Reminder to sign up for Oral exam 2 slot (link also on Canvas homepage)
E1 viewable on PL; score on Canvas
These announcements/first few cells were added since Thurs; picking up right before “Instance Attributes”
Mid-Course Survey
Course overall (constructive feedback): maybe a bit too much to do; 👎 loss of credit on VQs; wanting stuff to be posted sooner; want additional example problems (of ____ type)
Exam:
Pros: familiarity with PrairieLearn; on a day & at a time you like; multiple attempts & partial credit; scratch paper & calculator; didn’t have to write code on paper
Cons: lockers; computer lag; computer keyboards/mice; unfamiliar space in a basement; wifi interruptions; not enough time; no water/coffee; no COGS 18 proctors
Classes: Reviewing our VQ/textbook example
class Dog():
# class attribute - value will be the same for every Dog
sound = 'Woof'
# instance attribute
def __init__(self, name, breed):
self.name = name
self.breed = breed
self.age = 0
# method
def speak(self, n_times=2):
return self.sound * n_times
def have_birthday(self):
self.age += 1
# creating an instance
my_dog = Dog('Lexi', 'Italian Greyhound')
my_dog.age
0
my_dog.sound
'Woof'
my_dog.name
'Lexi'
my_dog.breed
'Italian Greyhound'
my_dog.age
0
my_dog.speak()
'WoofWoof'
my_dog.speak(4)
'WoofWoofWoofWoof'
my_dog.have_birthday()
my_dog.age
2
Classes: Reviewing our Spotify example so far
class Spotify:
platform_name = 'Spotify'
playlist = []
total_playlists = 0
def favorite_songs(self, songs_by_artists):
output_list = []
for artist, lst_songs in songs_by_artists.items():
for song in lst_songs:
output_list.append([song, artist])
return output_list
songs
{'Brandi Carlile': ['The Mother', 'The Story', 'Right on Time'],
'The Beatles': ['Hey Jude', 'Abbey Road']}
my_music=Spotify()
my_music.platform_name
'Spotify'
my_music.favorite_songs(songs_by_artists=songs)
[['The Mother', 'Brandi Carlile'],
['The Story', 'Brandi Carlile'],
['Right on Time', 'Brandi Carlile'],
['Hey Jude', 'The Beatles'],
['Abbey Road', 'The Beatles']]
songs
{'Brandi Carlile': ['The Mother', 'The Story', 'Right on Time'],
'The Beatles': ['Hey Jude', 'Abbey Road']}
for key, value in songs.items():
print(key)
print(value)
Brandi Carlile
['The Mother', 'The Story', 'Right on Time']
The Beatles
['Hey Jude', 'Abbey Road']
Instance Attributes#
The __init__()
Method/Function/Constructor#
Remember there are double underscores __
on each side!
The examples above are classes and objects in their simplest form, and but we can built upon it even more for real world applications.
To build upon it even more, we have to understand the built in __init__()
function.
All classes have a function called __init__()
or init method
So what is the point of __init__()
?#
The __init__()
method is to initialize an object’s attributes when it is created, also called an constructor
Constructors in any coding language are used to initialize an object’s state, in this case: object attributes
Our code should initially look like this:
Instance Attributes allow you to build more complex Class Methods and Class Attributes within your Class
Initially our code should look like this:
class Spotify:
platform_name = "Spotify"
playlists = []
total_playlists = 0
def __init__(self):
pass
def favorite_songs(self, songs_by_artist):
lst = []
for artist, songs in songs_by_artist.items():
for song in songs:
lst.append([song, artist])
return lst
The pass
is here as a placeholder for actual code.
How do we use our __init__
method?#
We can define that in the __init__
method or making instance attributes!
Instance Attributes are attributes defined INSIDE the __init__
initialize function.
There are two categories of Instance Attributes
The ones you define as an input parameter
The ones you continuously update while using Class Methods
An example of the Human Class:
class Human:
number_of_legs = 2
def __init__(self, name, height, age):
self.name = name
self.height = height
self.age = age
self.hobbies = []
How do we know what to put as an input parameter versus continuously updating?#
In our case for Spotify: Usernames
Let’s do a series of things!
Add The instance Attribute
username
as an input to our init methodAdd The instance Attribute
fav_artist
and assign it to a blank listAdd The instance Attribute
fav_playlist
and assign it to a blank listUpdate
favorite_songs
method to add your favorite artists tofav_artist
Update
favorite_songs
method to add your favorite songs tofav_playlist
Caution:
Instance Attributes defined as an input paramater besides
self
need to put in every time you make a Class Instance
class Spotify:
platform_name = "Spotify"
playlists = []
total_playlists = 0
def __init__(self, username):
self.username = username
self.fav_artist = []
self.fav_playlist = []
def favorite_songs(self, songs_by_artist):
lst = []
for artist, lst_songs in songs_by_artist.items():
for song in lst_songs:
lst.append([song, artist])
if artist not in self.fav_artist:
self.fav_artist.append(artist)
self.fav_playlist = lst
return lst
my_music = Spotify('ShanEllis')
my_music.username
'ShanEllis'
my_music.favorite_songs(songs)
[['The Mother', 'Brandi Carlile'],
['The Story', 'Brandi Carlile'],
['Right on Time', 'Brandi Carlile'],
['Hey Jude', 'The Beatles'],
['Abbey Road', 'The Beatles']]
my_music.fav_artist
['Brandi Carlile', 'The Beatles']
my_music.fav_playlist
[['The Mother', 'Brandi Carlile'],
['The Story', 'Brandi Carlile'],
['Right on Time', 'Brandi Carlile'],
['Hey Jude', 'The Beatles'],
['Abbey Road', 'The Beatles']]
Let’s say we wanted to show a string statement that told me what my username was?#
How can we make a string?#
Currently, these are all the ways you know how to make a string:
- str()
- ""
- ''
But what if we have some variables we want in our string statement?
Manual Way: String Concatenation
An Example of String Concatenation is:
element1 = 'carbon'
element2 = 'oxygen'
carbon_atoms = 2
oxygen_atoms = 1
Make the string statement:
"C02 is made up of 2 carbon atoms and 1 oxygen atom."
element1 = 'carbon'
element2 = 'oxygen'
carbon_atoms = 2
oxygen_atoms = 1
"C02 is made up of " + str(carbon_atoms) + ' ' + element1 + ' atoms and ' + str(oxygen_atoms) + ' ' + element2 + ' atom.'
'C02 is made up of 2 carbon atoms and 1 oxygen atom.'
Another way of doing this are called F-Strings
F-Strings#
You can put variables inside of a string by using f-strings.
To create an f-string you will need to put f"
, an f with double quotation marks infront of it.
Then put any variable name using curly braces {}
Lastly, end your statement with the remaining "
We can turn our previous string concatenation monster into this:
f"CO2 is made up of {carbon_atoms} {element1} and {oxygen_atoms} {element2} atom"
f"CO2 is made up of {carbon_atoms} {element1} and {oxygen_atoms} {element2} atom"
'CO2 is made up of 2 carbon and 1 oxygen atom'
Exercise:#
Make a class method user_info
that:
Takes in
year
, an integer, that represents the year when you first downloaded the Spotify AppOutputs an f-string statement that tells our username and how long we’ve had Spotify for
class Spotify:
platform_name = "Spotify"
playlists = []
total_playlists = 0
def __init__(self, username):
self.username = username
self.fav_artist = []
self.fav_playlist = []
def favorite_songs(self, songs_by_artist):
lst = []
for artist, lst_songs in songs_by_artist.items():
for song in lst_songs:
lst.append([song, artist])
if artist not in self.fav_artist:
self.fav_artist.append(artist)
self.fav_playlist = lst
return lst
def user_info(self, year):
return f"{self.username} first got a Spotify account in {year}"
my_music = Spotify('ShanEllis')
my_music.user_info(2006)
'ShanEllis first got a Spotify account in 2006'
Activity: Classes 2 Google Form:#
https://forms.gle/mBPD32aC3uV3s9hz7#
Class
CollegeStudent
where we have instance attributes name, age, major, and college.
Additionally, make a Class Method
introduction
that introduces themselves using the previously mentioned instance attributes
Hint: Remember to use f-strings!
# string concatenation
name = 'Shannon'
name2 = 'Ellis'
name + ' ' + name2
'Shannon Ellis'
f"{name} {name2}"
'Shannon Ellis'
class CollegeStudent():
def __init__(self, name, age, major, college):
self.name = name
self.age = age
self.major = major
self.college = college
def introduction(self):
return f"Hi, my name is {self.name}, and I am {self.age} years old. I study {self.major} at {self.college}."
my_student = CollegeStudent('Shannon', 36, 'Biology', "King's College")
my_student.name
'Shannon'
my_student.college
"King's College"
my_student.introduction()
"Hi, my name is Shannon, and I am 36 years old. I study Biology at King's College."
But what if we wanted to to create a playlist??#
Let’s add a Class Method called create_playlist
that returns a dictionary final_dict
!
Where the key is the playlist_name
and the values is an embedded list
Remember to put the self
paramater inside of our create_playlist
method!
It takes in three inputs:
playlist_name
, a string of your playlist namefav_artist
, a list of your favorite artist that you want in the playlistfav_list
, an embedded list of your favorite songs and artist!
class Spotify:
platform_name = "Spotify"
playlists = []
total_playlists = 0
def __init__(self, username):
self.username = username
self.fav_artist = []
self.fav_playlist = []
def favorite_songs(self, songs_by_artist):
lst = []
for artist, lst_songs in songs_by_artist.items():
for song in lst_songs:
lst.append([song, artist])
if artist not in self.fav_artist:
self.fav_artist.append(artist)
self.fav_playlist = lst
return lst
# additional method to think through
# if you fully understand, you know you're in great shape
# this is more complex than anything I would ask you to come up with on your own
# .....or would ever ask about in an oral exam <- NOT on an oral exam
def create_playlist(self, playlist_name, fav_artist=None, fav_list=None):
if fav_artist == None:
fav_artist = self.fav_artist
if fav_list == None:
fav_list = self.fav_playlist
lst = []
for song, artist in fav_list:
if artist in self.fav_artist:
lst.append((song,artist))
final_dict = {"name": playlist_name, "songs": lst}
self.playlists.append(final_dict)
return final_dict
my_music = Spotify('Emonx')
songs = {'starfall' : ['intentions', 'talk to me'],
'yayyoung' : ['Reality', 'If You Only Knew'],
'bixby' : ["don't make me", 'darling, he lied']}
my_music.favorite_songs(songs)
my_music.fav_artist
my_music.fav_playlist
my_music.create_playlist('Vibe City')
my_music.playlists
Inheritance#
You can think of this as inheriting Someone’s Will: property, certain finances, and etc.
This means that you can inherit all the properties of a previously defined Class:
Class Methods and Attributes and Instance Attributes
So let’s a new simple class: GradStudent
and have it inherit our CollegeStudent
Class for Activity 2
An example of inheritance would be
class Family_Member(Human):
pass
class CollegeStudent():
def __init__(self, name, age, major, college):
self.name = name
self.age = age
self.major = major
self.college = college
def introduction(self):
output = f"Hi my name is {self.name} and I am {self.age} years old. I am a {self.major} major at {self.college}."
return output
class GradStudent(CollegeStudent):
pass
Let’s see if any values of the original properties of the CollegeStudent
came through.
# this should error
my_gradstudent = GradStudent()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[136], line 1
----> 1 my_gradstudent = GradStudent()
TypeError: CollegeStudent.__init__() missing 4 required positional arguments: 'name', 'age', 'major', and 'college'
my_gradstudent = GradStudent('Emanoel Agbayani', 23, 'Cognitive Science', 'UCSD')
my_gradstudent.introduction()
'Hi my name is Emanoel Agbayani and I am 23 years old. I am a Cognitive Science major at UCSD.'
Let’s say now that we are older, we will need to show that we are a Graduate Student#
Create a new Class Method introduction_2
that gives us a string statement that we are a Graduate Student
class Grad_Student(CollegeStudent):
def introduction_2(self):
my_gradstudent = Grad_Student('Emanoel Agbayani', 26, 'Cognitive Science', 'UCSD')
my_gradstudent.introduction_2()
Now you know how to create Classes, Class Attributes and Methods, and Instance Attributes!
Remember!!!
Attributes can be thought of as Variable Assignment !!!
Methods can be thought of as Functions!!!
On-Campus ways to be involved with Coding/Machine Learning:#
Triton Prosthetics Society: https://discord.gg/3pTCkc4BGc