Previous Lecture Lecture 6 Next Lecture

Lecture 6, Thu 04/20

Inheritance cont., Runtime Analysis

Recorded Lecture: 4_20_23

Extending Superclass Methods

class Cow(Animal):
	def getSound(self):
		s = "Using Super class getSound method\n"
		s += Animal.getSound() + "\n" # Uses Animal.getSound method
		s += "Extending it with our own getSound functionality" + "\n"
		s += "{}!!!".format(self.sound, self.sound)
		return s

# Output:
# Using super class getSound method
# I'm an Animal!!!
# Extending it with our own getSound functionality
# Moo!!!

Extending Constructors in a Child Class

# In Cow.py

    def __init__(self, species=None, name=None, sound=None):
		super().__init__(species, name)
		#Animal.__init__(self, species, name) also works
		self.sound = sound
c = Cow("Cow", "Betsy", "Moo") # Passes in data for Animal AND Cow
a = Animal("Unicorn", "Lala")

zoo = [c, a]

for i in zoo:
	print(i.getAttributes())
	print(i.getSound())
	print("---")

Inheritance and Exceptions

class A(Exception):
	pass

class B(A): # B inherits from A (B IS-A A type)
	pass

class C(Exception):
	pass

try:
	x = int(input("Enter a positive number: "))
	if x < 0:
		raise B() # Change this to A() and C() and observe...
except C:
	print("Exception of type C caught")
except A:
	print("Exception of type A caught")
except B:
	print("Exception of type B caught") # Will never get called
except Exception:
	print("Exception of type Exception caught")

print("Resuming execution")

Algorithm Analysis

import time

def f1(n):
	l = []
	for i in range(n):
		l.insert(0,i)
	return

def f2(n):
	l = []
	for i in range(n):
		l.append(i)
	return

print("starting f1")
start = time.time()
f1(200000)
end = time.time()
print("time elapsed: ", end - start, "seconds")

print("starting f2")
start = time.time()
f2(200000)
end = time.time()
print("time elapsed: ", end - start, "seconds")

Asymptotic Behavior

for i in range(10):
	print(i)
def f(n):
	for i in range(n):
		print(i)

Order of magnitude function (Big-O)

def f(n)
	x = 0
	for i in range(n):
		for j in range(n):
			x = i + j
def f(n):
    for i in range(n):
        return i