self.__inventory = inventory
def get_inventory(self):
return self.__inventory
inventory = property(get_inventory, set_inventory)
def buy_Product(self, amount):
self.__inventory = self.__inventory - amount
def __str__(self):
return '{0} - price: ${1:.2f}, inventory:
{2:d}'.format(self.__description, self.__price,
self.__inventory)
The product.py file incorporates all the attributes and methods for the Product
class into a single module. You can now use your Product class in any of your
Python scripts by simply importing the class from the product.py file.
- Save the product.py file.
- Open the text editor again and create the script1403.py file. Here’s the code to
enter into the file:
Click here to view code image
#!/usr/bin/python3
from product import Product
prod1 = Product('carrot', 1.25, 10)
print(prod1)
print('Buying 4 carrots...')
prod1.buy_Product(4)
print(prod1)
print('Changing the price to $1.50...')
prod1.price = 1.50
print(prod1)
The code first uses the from statement to reference the Product class from the
product.py module file. (Make sure you have the product.py file in the same
folder as the script1403.py file.)
- Save the script1403.py file in the same folder where you saved the
product.py file. - Run the script1403.py file from the command prompt.
Here’s what you should see when you run the script1403.py file:
Click here to view code image
pi@raspberrypi ~$ python3 script1403.py
carrot - price: $1.25, inventory: 10
Buying 4 carrots...
carrot - price: $1.25, inventory: 6
Changing the price to $1.50...
carrot - price: $1.50, inventory: 6
pi@raspberrypi ~$
The script uses the Product class that you defined in the product.py file to