Difference between revisions of "CSC111 Exercises on Classes and Objects"
(→Exercise 3) |
(→Exercise 3) |
||
Line 37: | Line 37: | ||
Go back to Bob containing a ''private'' member variable. | Go back to Bob containing a ''private'' member variable. | ||
;Question 1 | ;Question 1 | ||
− | : Create 2 objects of type Bob, each containing the values 45 and 70, respectively, and save them in a list called '''L''' | + | : Create 2 objects of type Bob, each containing the values 45 and 70, respectively, and save them in a list called '''L'''. Verify that the list contains these 2 objects. |
<br /> | <br /> | ||
; Question 2 | ; Question 2 | ||
− | : Change the value of the first element of the list to 10, and the value of the second one to 20. | + | : Change the value of the first element of the list to 10, and the value of the second one to 20. Verify that the change was made. |
<br /> | <br /> | ||
;Question 3 | ;Question 3 | ||
− | : Create 20 objects of type Bob, each containing 1, 2, 3,... 20, respectively, and save them in a list called '''L2''' | + | : Create 20 objects of type Bob, each containing 1, 2, 3,... 20, respectively, and save them in a list called '''L2'''. Display the contents of the list. |
<br /> | <br /> | ||
;Question 4 | ;Question 4 | ||
− | : Reset the values in all 20 objects in '''L2''' to 0. | + | : Reset the values in all 20 objects in '''L2''' to 0. Verify that the reset operation was successful. |
<br /> | <br /> | ||
Revision as of 09:51, 14 April 2014
--D. Thiebaut (talk) 13:05, 13 April 2014 (EDT)
Contents
Exercise 1
class Bob:
def __init__( self ):
self._a = None
def setA( self, x ):
self._a = x
def getA( self ):
return self._a
- Question 1
- Create an object of type Bob, call it x, and set its member variable to 4
- Question 2
- Add 10 to the member variable of x.
- Question 3
- print the object contents of Object x. First by getting _a from x and printing it, then by adding a new method to Bob so that we can print objects just by passing them to print()
Exercise 2
This exercise is very similar to Exercise 1, but the definition of self._a is now self.a. Answer the same 3 questions.
Exercise 3
Go back to Bob containing a private member variable.
- Question 1
- Create 2 objects of type Bob, each containing the values 45 and 70, respectively, and save them in a list called L. Verify that the list contains these 2 objects.
- Question 2
- Change the value of the first element of the list to 10, and the value of the second one to 20. Verify that the change was made.
- Question 3
- Create 20 objects of type Bob, each containing 1, 2, 3,... 20, respectively, and save them in a list called L2. Display the contents of the list.
- Question 4
- Reset the values in all 20 objects in L2 to 0. Verify that the reset operation was successful.
Exercise 4
This exercise is very similar to Exercise 3, but we construct a new class that contains a list of objects of type Bob. Answer the same questions as in Exercise 3.