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

(singke) #1
TypeError: __init__() missing 3 required positional arguments: 'desc', 'price', and
'inventory'
>>>

To solve this problem, just as with Python functions, the constructor method lets you define default
values in the parameters (see Hour 12, “Creating Functions”), as in this example:


Click here to view code image


def __init__(self, description = 'new product', price = 0, inventory = 0):
self.__description = description
self.__price = price
self.__inventory = inventory

Now if you create a new instance of the Product class without specifying any default values,
Python uses the default values you defined in the class constructor, as shown here:


Click here to view code image


>>> prod5 = Product()
>>> prod5.get_description()
'new product'
>>> prod5.get_price()
0.0
>>> prod5.get_inventory()
0
>>>

Now your class constructor is even more versatile!


Customizing Output


The next thing to tackle is displaying the class instance. So far you’ve had to use the print()
statement to display the individual attributes from the class instance, using the get_ methods.
However, if you have to display your class data multiple times in your program code, that could get
old. Python provides an easier way to do it.


You just need to define the str() helper method for your class to tell Python how to display
the class object as a string value. Any time your program references the class instance as a string
(such as when you use it in a print() statement), Python calls the str() method from the
class definition. All you need to do is return a string value from the str() method that formats
the class object attributes as strings. Here’s what the str() method could look like for the
Product class:


Click here to view code image


def __str__(self):
return '{0} - price: ${1:.2f}, inventory:
{2:d}'.format(self.__description, self.__price, self.__inventory)

Now, to display the class instance attribute values, you can just reference the instance variable in the
print() statement, as shown here:


Click here to view code image


>>> prod6 = Product('banana', 1.50, 30)
>>> print(prod6)
banana – price: $1.50, inventory: 30
>>>
Free download pdf