>>> prod1.price = 1.50
>>> print('The new price is', prod1.price)
The new price is 1.50
>>>
The prod1.price property allows you to both set and retrieve the __price attribute value in
your program code.
Sharing Your Code with Class Modules
The whole point of creating Python object-oriented classes is that you can reuse the same code in any
program that uses that object. If you combine the class definition code with your program code,
sharing your class objects is more difficult.
The key to OOP in Python is to create separate modules for each object class. That way, you can just
import the object class file that you need for any program that uses that type of object.
It’s somewhat common practice to name the object class module the same name as the class. Doing so
makes it easier to identify and import your classes. The following Try It Yourself walks through
creating a module file for the Product class and then using it in a separate application script.
Try It Yourself: Create a Class Module
In the following steps, you’ll create two Python script files. One file will contain the
code that defines the Product class, and the other file will contain the script you’ll
run to use the class. Here’s what you do:
- Open a text editor and create the file product.py. Here’s the code that you need
to enter into the file:
Click here to view code image
#!/usr/bin/python3
class Product:
def __init__(self, description, price, quantity):
self.__description = description
self.__price = price
self.__inventory = quantity
def set_description(self, description):
self.__description = description
def get_description(self):
return self.__description
description = property(get_description, set_description)
def set_price(self, price):
self.__price = price
def get_price(self):
return self.__price
price = property(get_price, set_price)
def set_inventory(self, inventory):