Let's revisit pencil and paper tracing-- walking through programs and showing how memory changes for each piece of code executed.
First, a review of tracing and Python's parameter passing rules. Consider the following code:
def func(x, someList): g=83 #... some other code
# main g = 99 list=[3,4] func(22,list)
1. Circle and label the a. formal parameters b. local variables c. actual parameters
2. When a scalar is sent as a parameter, what is actually sent?
3. When a list is sent as a parameter, what is actually sent?
4. Trace the program above using boxes and arrows.
Object-Oriented Tracing Rules1. For an object creation statement, draw a multi-part box and label each sub-box with the name of the field.
What should be drawn for the statement: c1= Coordinate(3,4)
2. Objects are sent by-reference, just like lists. This includes the parameter self in an object-oriented function.
Show how a call to the distance function of class Coordinate would be trace.
3. Some object-oriented functions are called in a special way. Which ones? If you are tracing exactly how Python executes programs, you'll need to be aware of these special functions.
Consider the Person class and main program on the following page.
1. Grab the attached file and run it. Does the program work? Will it work for any main program, i.e., no matter what social network is created? If not, fix it.
2. Trace the Person Program using the rules outlined above. You need not trace the calls to the __init__ function
class Person: def __init__(self,name): self.name=name self.friends=[]
def __str__(self): return self.name
def add_friend(self,friend): self.friends.append(friend)
def list_friends(self): i=0 while i<len(self.friends): print self.friends[i] i=i+1
def friends_of_friends(self): fofs=[] i=0 while i<len(self.friends): friend=self.friends[i] j=0 while j<len(friend.friends): fof=friend.friends[j] if not (fof in self.friends): fofs.append(fof) j=j+1 i=i+1 return fofs
# main joe = Person("joe") mary = Person("mary") bill = Person("bill") susan = Person("susan") mary.add_friend(bill) joe.add_friend(mary) joe.add_friend(bill) mary.add_friend(susan) fofs = joe.friends_of_friends() i=0 while i<len(fofs): print fofs[i] i=i+1 |
Attachments (1)
-
person.py - on Mar 11, 2009 12:29 PM by David Wolber (version 1)
1k
Download
|