Skip to the content.

Code 401 Class 04 Reading Notes

Classes and Objects

Classes are a template to create objects. Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes.

Example:

class MyClass:
  var = "blah"

  def function(self):
      print("This is a message inside the class.")

myobjectx = Myclass() #assigning class to an object

Accessing Object Variable

Accessing the variable inside of the newly created object ‘myobjectx’ you would do the following:

class MyClass:
  var = "blah"

  def function(self):
      print("This is a message inside the class.")

myobjectx = Myclass() #assigning class to an object

myobjectx.variable

/the below will print
print(myobjectx.variable)

One can create multiple different objects are the same class(have the same variables and functions defined). If we were to define another object with the “MyClass” class and then change the string in the variable above.

class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()
myobjecty = MyClass()

myobjecty.variable = "yackity"

# Then print out both values
print(myobjectx.variable)
print(myobjecty.variable)

prints: blah
prints: yackity

Accessing Object Functions

Accessing a function inside of an object is similar to accessing a variable:

class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()

myobjectx.function()

init()

The __init__ function, is a special function that is called when the class is being initiated.

class NumberHolder:

   def __init__(self, number):
       self.number = number

Exercise

Define two new vehicles called car1 and car2. Set car1 to be a red convertible worth $60,0000 with a name of Fer, and car2 to be a blue van named Jump worth $10,0000.

class Vehicle:
    name = ""
    kind = "car"
    color = ""
    value = 100.00
    def description(self):
        desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)
        return desc_str
# your code goes here
    car1 = Vehicle()
    car1.name = "Fer"
    car1.kind = "convertible"
    car1.color = "red"
    car1.value = 60000.00

    car2 = Vehicle() 
    car2.name = "Jump"
    car2.kind = "Van"
    car2.color = "blue"
    car2.value = 10000.00

# test code
print(car1.description())
print(car2.description())


Thinking Recursively in Python

My soul

(This art speaks to my soul)

Dear Pythonic Santa

Thinking of what Santa clause has to do in order to deliver presents, he has a list of houses he loops through. He goes to a house, drops off presents, eats the cookies and milk, and moves on to the next house on the list. This is called an iterative algorithm.

houses = ["Eric's house", "Kenny's house", "Kyle's house", "Stan's house"]

def deliver_presents_iteratively():
  for house in houses:
    print("Delivering presents to", house)

>>> deliver_presents_iteratively()
Delivering presents to Eric's house
Delivering presents to Kenny's house
Delivering presents to Kyle's house
Delivering presents to Stan's house

A recursive way to do this, is to divide the work of delivering presents among his elves:

  1. Appoint an elf and give all the work to him
  2. Assign titles and responsibilities to the elves based on the number of houses for which they are responsible:
    • > 1 He is a manager and can appoint two elves and divide his work among them
    • = 1 He is a worker and has to deliver the presents to the house assigned to him.

The typical recursive algorithm structure.

Recursive Present Delivery

The recursive algorithm in python

houses = ["Eric's house", "Kenny's house", "Kyle's house", "Stan's house"]

# Each function call represents an elf doing his work
def deliver_presents_recursively(houses):
    # Worker elf doing his work
    if len(houses) == 1:
        house = houses[0]
        print("Delivering presents to", house)

    # Manager elf doing his work
    else:
      mid = len(houses) // 2
      first_half = houses[:mid]
      second_half = houses[mid:]

      # Divides his work among two elves
      deliver_presents_recursively(first_half)
        deliver_presents_recursively(second_half)

Recursive Functions in Python

A recursive function is a function defined in terms of itself via self-referential expressions.

This means that the function will continue to call itself and repeat its behavior until some condition is meat to return a result.

Example:

def factorial_recursive(n):
    # Base case: 1! = 1
    if n == 1:
        return 1

    # Recursive case: n! = n * (n-1)!
    else:
        return n * factorial_recursive(n-1)

>>> factorial_recursive(5)
120

Growing call stack

Maintaining State

To maintain state during recursion:

def sum_recursive(current_number, accumulated_sum):
    # Base case
    # Return the final state
    if current_number == 11:
        return accumulated_sum

    # Recursive case
    # Thread a the state through the recursive call
    else:
        return sum_recursive(current_number + 1, accumulated_sum + current_number)

>>> sum_recursive(1,0)
55

Pesky Details

To prevent stack over flow use the below limitation

import sys
sys.getrecursionlimit()

Things I want to know more about

I’d like to dive in to steps of basic recursion to a little more complex, to a little more, etc.

<—BACK