Classes#

Open In Colab

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 the except instead.

Q: just to clarify attributes store information, and methods are functions?
A: Yup! We’ll deepen this knowledge today!

Announcements

Due this week:

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)
type(y)

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

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

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.

Exercise: Adding more Class Attributes#

  1. Add a class attribute called playlist and make it a empty list

  2. Add a another class attribute called total_playlists and assign it 0

  3. Run 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

Activity: Classes 1 Google Form:#

https://forms.gle/pcpJCwN8Y8eKszEU7#

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

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!

Caution!#

What happens if I do not put self in my Class Methods?

class Spotify2:
    platform_name = "Spotify"
    playlists = []
    total_playlists = 0
    
    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)

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?

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

  1. The ones you define as an input parameter

  2. 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
        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!

  1. Add The instance Attribute username as an input to our init method

  2. Add The instance Attribute fav_artist and assign it to a blank list

  3. Add The instance Attribute fav_playlistand assign it to a blank list

  4. Update favorite_songs method to add your favorite artists to fav_artist

  5. Update favorite_songs method to add your favorite songs to fav_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):
        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

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.'

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"

Exercise:#

Make a class method user_info that:

  • Takes in year , an integer, that represents the year when you first downloaded the Spotify App

  • Outputs 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, songs in songs_by_artist.items():
            for song in songs:
                lst.append([song, artist])
            if artist not in self.fav_artist: 
                self.fav_artist.append(artist)
                
        self.fav_playlist = lst
        return lst

Activity: Classes 2 Google Form:#

https://forms.gle/mBPD32aC3uV3s9hz7#

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 name

  • fav_artist, a list of your favorite artist that you want in the playlist

  • fav_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, songs in songs_by_artist.items():
            for song in songs:
                lst.append([song, artist])
            if artist not in self.fav_artist:
                self.fav_artist.append(artist)
        self.fav_playlist = lst
        return lst

    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.fav_playlist
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.

my_gradstudent = GradStudent()
my_gradstudent = GradStudent('Emanoel Agbayani', 23, 'Cognitive Science', 'UCSD')
my_gradstudent.introduction()

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!!!

Course Announcements

  • CL5 due Friday 5/9/25

  • VQ11 due Mon

  • A4 due next Sunday 5/11/2

On-Campus ways to be involved with Coding/Machine Learning:#