Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
pi@raspberrypi ~$ python3 script1401.py
carrot – price: $1.00, inventory: 10
pi@raspberrypi ~$

The program code contained in the script1401.py file creates an instance of the Product
class; sets the description, price, and __inventory attribute values (using the
appropriate setter methods); and then retrieves the attribute values using the getter methods.


So far, so good. But things are a bit cumbersome in terms of using the class methods. You had to go
through a lot of work to create the class, set the initial values for the attributes, and then retrieve the
attribute values using the getters. Fortunately, Python has some helper methods that help make your
life easier!


Adding Helper Methods to Your Code


Besides the accessor and mutator methods, there are a few other methods you can create for your
classes that help make using classes much easier. The following sections go through some of the most
common helper class methods that you’ll want to use when working with classes in your Python
programs.


Constructors


It can get somewhat old trying to set attribute values using the set_ mutator methods, especially if
you have lots of attributes in a class. Using class constructor methods is a popular simple way to
instantiate a new instance of a class with default values.


Python provides a special method called init() that it calls when you instantiate a new class
instance. You can define the init() method in your class code to do any type of work when
the class instance is created, including assign default values to attributes. The init() method
requires parameters for each attribute that you want to define a value for, as shown here:


Click here to view code image


def __init__(self, description, price, inventory):
self.__description = description
self.__price = price
self.__inventory = inventory

Now when you create the instance of the Product class, you must define the initial values directly
in the class constructor:


Click here to view code image


>>> prod3 = Product('tomato', 2.00, 20)
>>> print('{0} – price: ${1:.2f}, inventory:
{2:d}'.format(prod1.get_description(), prod1.get_price(),
prod1.get_inventory()))
tomato – price: $2.00, inventory: 20
>>>

This makes creating a new instance of a class a lot easier! The only downside is that you must specify
the default values, and if you don’t, you get an error message, like this:


Click here to view code image


>>> prod1 = Product()
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
prod1 = Product()
Free download pdf