Lecture 25: Classes & Objects

August 3rd, 2021


Today: JSON, matplotlib (finishing up from lecture 24), classes, and objects

Announcements

Object Oriented Programming (OOP)

Classes and Objects

Example of a Class in Python

Counter Example Zip
    
class Counter:

    # Constructor (two underscores - double underscores - known as 'dunder')
    def __init__(self): 
        self.ticket_num = 0 # "instance" variable 

    # Method (function) that returns the next ticket value
    def next_value(self):
        self.ticket_numm += 1
        return self.ticket_num
    

Classes in Action

Objects are Mutable:
- When you pass an object into as a parameter, changes to the object in that function persist after the function ends

    
from counter import Counter # import the Class

def count_two_times(counter):
    for i in range(2):
        print(counter.next_value())

def main():
    count1 = Counter()
    count2 = Counter()
    print('Count1: ')
    count_two_times(count1)
    print('Count2: ')
    count_two_times(count2)
    print('Count1: ')
    count_two_times(count1)
    

Output:

Count1:
1
2
Count2:
1
2
Count1:
3
4

How to Write a Class in Python

    
class Classname:
    # Constructor
    def __init__(self, additional parameters):
        # body of code
        self.variable_name = value # example instance variable
    
    # Method
    def method_name(self, additional parameters):
        # body of code
    

Constructor of a Class

Instance Variables


Methods (functions) in a Class

Another Example: Students

Student Class Example Zip