eggplant
>>> print(prod1.description)
carrot
>>>
Now you have two separate instances of the Product class: prod1 and prod2. Each instance has
its own attribute values.
Default Attribute Values
Defining attributes on the fly as you use a class instance isn’t good programming practice. It’s better
to define the class attributes inside the class definition code so that they’re documented as part of the
class. You can do that and set default values for the attributes all at the same time, like this:
Click here to view code image
>>> class Product:
description = "new product"
price = 1.00
inventory = 10
>>>
Now when you instantiate a new instance of the Product class, the instance has values set for the
description, price, and inventory attributes, as shown here:
Click here to view code image
>>> prod1 = Product()
>>> print('{0} - price: ${1:.2f}, inventory: {2:d}'.format(prod1.description,
prod1.price, prod1.inventory))
new product – price: $1.00, inventory: 10
>>>
After you create the new class instance, you can replace the existing values at any time, as in the
following example:
Click here to view code image
>>> prod1.description = 'tomato'
>>> print('{0} - price: ${1:.2f}, inventory: {2:d}'.format(prod1.description,
prod1.price, prod1.inventory))
tomato – price: $1.00, inventory: 10
>>>
The description attribute of the prod1 instance now has the new value that you assigned.
Defining Class Methods
Classes consist of more than just a bunch of attributes. You also need to have methods for handling
the attributes. There are three different types of class methods available:
Mutator methods
Accessor methods
Helper methods
The following sections discuss the difference between mutator and accessor methods, and then you’ll
learn more about the helper methods.
Mutator Methods