The Product class creates an instance of a product with three attributes
- the product description, price, and inventory
You can also create a docstring value for each individual method inside the class, as shown here:
Click here to view code image
def get_description(self):
"""The description contains the product type"""
return self.__description
To view a method’s docstring, you just add the doc attribute to the method in the instance, like
this:
Click here to view code image
>>> prod8 = Product()
>>> prod8.get_description.__doc__
The description contains the product type
>>>
Now you have a way to share your comments on the class with others who may use your code in their
own projects.
The property() Helper Method
So far you have setter and getter methods defined to interface with the attributes you define for a
class. However, it can get somewhat cumbersome trying to use the set and get methods all the
time for each method. To solve this problem, Python provides the property() method.
The property() method creates a method that combines the setter and getter methods, along with
the destructor and a docstring for an attribute, into a single method. Python calls the appropriate
method, based on how you use the property() method in your code.
This is the syntax for defining the property() method in a class:
Click here to view code image
method = property(setter, getter, destructor, docstring)
You don’t have to define all four parameters in the property() method. You can define a single
parameter to create only a setter method; two methods to create only setter and getter methods, three
methods for the setter, getter, and destructor; or all four parameters to create all four methods.
Here’s an example of what you can add to the end of a Product class to create the property()
methods for each attribute:
Click here to view code image
description = property(get_description, set_description)
price = property(get_price, set_price)
inventory = property(get_inventory, set_inventory)
Once you define the property() methods for the attributes, you can set or get the individual
attributes by referencing their property() methods, as shown here:
Click here to view code image
>>> prod1 = Product('carrot', 1.00, 10)
>>> print(prod1)
carrot – price: $1.00, inventory: 10