Disc 07
Disc 07
For example, consider the class Student. Each of you as individuals is an instance
of this class. So, a student Angela would be an instance of the class Student.
Details that all CS 61A students have, such as name, are called instance attributes.
Every student has these attributes, but their values differ from student to student.
An attribute that is shared among all instances of Student is known as a class
attribute. An example would be the students attribute; the number of students
that exist is not a property of any given student but rather of all of them.
All students are able to do homework, attend lecture, and go to office hours. When
functions belong to a specific object, they are said to be methods. In this case,
these actions would be bound methods of Student objects.
Questions
1.1 Below we have defined the classes Professor and Student, implementing some of
what was described above. Remember that we pass the self argument implicitly to
instance methods when using dot-notation. There are more questions on the next
page.
class Student:
students = 0 # this is a class attribute
def __init__(self, name, ta):
self.name = name # this is an instance attribute
self.understanding = 0
Student.students += 1
print("There are now", Student.students, "students")
ta.add_student(self)
class Professor:
def __init__(self, name):
self.name = name
self.students = {}
Note: This worksheet is a problem bank—most TAs will not cover all the problems in discussion section.
Object-Oriented Programming 3
>>> elle.visit_office_hours(callahan)
>>> elle.visit_office_hours(Professor("Paulette"))
>>> elle.understanding
>>> x
Note: This worksheet is a problem bank—most TAs will not cover all the problems in discussion section.
4 Object-Oriented Programming
1.2 In this question, we will implement a special version of a list called a MinList. A
MinList acts similarly to a list in that you can append items and pop items from it,
but it only can pop the smallest number.
Each instance also contains an attribute size that represents how many elements
it contains. Remember to update size in append and pop!
class MinList:
"""A list that can only pop the smallest element """
def __init__(self):
self.items = _______________________________
self.size = 0
def pop(self):
""" Removes and returns the smallest item from the MinList
>>> m = MinList()
>>> m.append(4)
>>> m.append(1)
>>> m.append(5)
>>> m.pop()
1
>>> m.size
2
"""
Note: This worksheet is a problem bank—most TAs will not cover all the problems in discussion section.
Object-Oriented Programming 5
1.3 Tutorial:
We now want to write three different classes, Server, Client, and Email to simulate
email. Fill in the definitions below to finish the implementation! There are more
methods to fill out on the next page.
We suggest that you approach this problem by first filling out the Email class, then
fill out the register client method of Server, then implement the Client class,
and lastly fill out the send method of the Server class.
class Email:
"""Every email object has 3 instance attributes: the
message, the sender name, and the recipient name.
"""
def __init__(self, msg, sender_name, recipient_name):
class Server:
"""Each Server has an instance attribute clients, which
is a dictionary that associates client names with
client objects.
"""
def __init__(self):
self.clients = {}
Note: This worksheet is a problem bank—most TAs will not cover all the problems in discussion section.
6 Object-Oriented Programming
class Client:
"""Every Client has instance attributes name (which is
used for addressing emails to the client), server
(which is used to send emails out to other clients), and
inbox (a list of all emails the client has received).
"""
def __init__(self, server, name):
self.inbox = []
Note: This worksheet is a problem bank—most TAs will not cover all the problems in discussion section.
Object-Oriented Programming 7
2 Inheritance
Python classes can implement a useful abstraction technique known as inheritance.
To illustrate this concept, consider the following Dog and Cat classes.
class Dog():
def __init__(self, name, owner):
self.is_alive = True
self.name = name
self.owner = owner
def eat(self, thing):
print(self.name + " ate a " + str(thing) + "!")
def talk(self):
print(self.name + " says woof!")
class Cat():
def __init__(self, name, owner, lives=9):
self.is_alive = True
self.name = name
self.owner = owner
self.lives = lives
def eat(self, thing):
print(self.name + " ate a " + str(thing) + "!")
def talk(self):
print(self.name + " says meow!")
Notice that because dogs and cats share a lot of similar qualities, there is a lot of
repeated code! To avoid redefining attributes and methods for similar classes, we
can write a single superclass from which the similar classes inherit. For example,
we can write a class called Pet and redefine Dog as a subclass of Pet:
class Pet():
def __init__(self, name, owner):
self.is_alive = True # It's alive!!!
self.name = name
self.owner = owner
def eat(self, thing):
print(self.name + " ate a " + str(thing) + "!")
def talk(self):
print(self.name)
class Dog(Pet):
def talk(self):
print(self.name + ' says woof!')
Note: This worksheet is a problem bank—most TAs will not cover all the problems in discussion section.
8 Object-Oriented Programming
Questions
2.1 Below is a skeleton for the Cat class, which inherits from the Pet class. To com-
plete the implementation, override the init and talk methods and add a new
lose_life method.
Hint: You can call the init method of Pet to set a cat’s name and owner.
class Cat(Pet):
def __init__(self, name, owner, lives=9):
def talk(self):
""" Print out a cat's greeting.
def lose_life(self):
"""Decrements a cat's life by 1. When lives reaches zero, 'is_alive'
becomes False. If this is called after lives has reached zero, print out
that the cat has no more lives to lose.
"""
Note: This worksheet is a problem bank—most TAs will not cover all the problems in discussion section.
Object-Oriented Programming 9
2.2 Tutorial: More cats! Fill in this implemention of a class called NoisyCat, which is
just like a normal Cat. However, NoisyCat talks a lot – twice as much as a regular
Cat! Make sure to also fill in the repr method for NoisyCat, so we know how
to construct it! As a hint: You can use several string formatting methods to make
this easier.
E.g.:
def talk(self):
"""Talks twice as much as a regular cat.
def __repr__(self):
"""The interpreter-readable representation of a NoisyCat
Note: This worksheet is a problem bank—most TAs will not cover all the problems in discussion section.