Practice Problems

Lecture 10

Answer each number in a separate cell

Rename this notebook with your last name and the lecture

ex. CychB_10

Turn-in this notebook on TritonEd by the end of class

1. Classes

  • Create a class called Rectangle with width and height (w,h) as attributes
  • include a docstring
  • define two methods: area and perimeter
    • area calculates the area of the rectangle
    • perimeter calculates the perimeter of the rectangle
    • include a docstring with each method
  • Create a new instance of the Rectangle class with width 1 and length 4.
  • Create a second instance of the Rectangle class with width 4 and length 4
  • Call the method area( ) on both your first and second Rectangle object. Print the area
  • Call the method perimeter( ) on your second Rectangle object and save the outcome in a new variable. Print the value of the new variable

2. Classes in modules

  • Rename the Rectangle class Rect and save it to a module called Now we can import and re-use it whenever we like.
  • Do this by:
    • copy the class definition code block into your text file window
      • save it to this directory using the %%writefile magic command
    • import the Rect class into your Practice Problems notebook
    • Create a new instance of the Rect class.
    • Call the methods area( ) and perimeter( ) and print out the output

3. Copies

  • using your Shapes module, make an instance of Rectangle called rec with a length and width of 2 and 4
  • make a copy of rec called copy
  • make a deepcopy of copy called deep
  • change the length of copy to 3
  • print out rec.length, copy.length, deep.length

Reminder for Python 3 users: If you have changed a module and you need to import the changes into the jupyter notebook, then execute the command:

from importlib import reload

Then you can use this command to refresh your module in the notebook:


In [ ]: