Lecture 26: Classes & Memory

August 4th, 2021


Today: More about classes and memory

Announcements

What does it take to write big scale software?

Classes and Objects

Classes Review

dog.py

class Dog:
    
    # constructor 
    def __init__(self):
        self.times_barked = 0 # instance variable 

    # instance method
    def bark(self):
        print('woof')
        self.times_barked += 1

Let's break down the above class

1. Instance Variables - what sub-variables does each instance store?

self.times_barked

2. Instance Methods - what methods can you call on an instance?

# instance method
def bark(self):
    print('woof')
    self.times_barked += 1

3. Constructor - what happens when you make a new one?

# constructor 
def __init__(self):
    self.times_barked = 0 # instance variable 

Let's review how we use classes

life.py

def main():
    simba = Dog()
    juno = Dog()
    simba.bark()
    juno.bark()
    simba.bark()

    print(simba.__dict__)
    print(juno.__dict__)

What is simba.__dict__?

What is self?

Classes Split Up Work Just Like Functions

Next step in writing larger programs: Better Understand Memory

What does this do?

Slides borrowed from Piech + Sahami 2020





The Stack

The Heap

Let's take a closer look: x = x + 1

Memory Example with Mutiple Functions














Let's checkout how Classes & Objects use memory

Slides borrowed from Piech + Sahami 2020






















Challenge for You