Working with Classes Preparation
Overview
Once you know how to define your own class, there are lots of ways that you can use and interact with it. Today we’ll focus on how you can use your own classes as parameters and return values.
Basic Learning Objectives
Before class, you should be able to:
- Pass an object of your own class to a function
- Return an object of your own class
- Define the
__str__method - Explain the difference between class variables and instance variables
Advanced Learning Objectives
After class, you should be able to:
- Define several classes that work together to solve a problem
Resources
You should read the following:
- Runestone 13.6 Objects as Arguments and Parameters
- Runestone 13.7
- Runestone 13.8 Instances as Reeturn Values
- Runestone 13.9 Class Variables and Instance Variables
Checks
Submit answers to the following on Moodle:
- (13.7 Check) Create a class called Cereal that accepts three inputs: 2 strings and 1 integer, and assigns them to 3 instance variables in the constructor:
name,brand, andfiber. When an instance ofCerealis printed, the user should see the following:“[name] cereal is produced by [brand] and has [fiber integer] grams of fiber in every serving!”To the variable namec1, assign an instance ofCerealwhose name is “Corn Flakes”, brand is “Kellogg’s”, and fiber is 2. To the variable namec2, assign an instance ofCerealwhose name is “Honey Nut Cheerios”, brand is “General Mills”, and fiber is 3. Print both. - (13.13.3) Define a class called
BankAccountthat accepts the name you want associated with your bank account in a string, and an integer that represents the amount of money in the account. The constructor should initialize two instance variables from those inputs:nameandamt. Add a string method so that when you print an instance ofBankAccount, you see"Your account, [name goes here], has [start_amt goes here] dollars."Create an instance of this class with “Bob” as the name and 100 as the amount. Save this to the variablet1.