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

(singke) #1

This is yet another method to make your life a lot easier!


Deleting Class Instances


Handling memory management in Python programs is normally a lot easier than in other programming
languages. By default, Python recognizes when a class instance is no longer in use and removes it
from memory. However, there may be times when a program needs to do some type of “cleanup”
work for the class before Python removes it from memory.


You can specify a helper method that Python automatically attempts to run just before it removes the
instance from memory. Such methods are called destructors.


Destructors come in handy with a class that works with files to ensure that the files are properly
closed before the class instance is removed.


You use the del() helper method to define any final statements to process before Python
removes the class instance from memory:


def __del__(self):
statements

The del() method doesn’t allow you to pass any parameters into the method. All the
statements that you specify in the method need to be self-contained and must not rely on any data from
the main program.


Watch Out!: Running Destructors
Python processes a class destructor any time it automatically removes a class instance
from memory or when you use the del statement on the class instance. However, when
the Python interpreter shuts down, there are no guarantees that Python will be able to
run the descriptor class for any active class instances.

Documenting the Class


Object-oriented classes are meant to be shared. Therefore, it’s important that you document your
Python classes so that anyone else who needs to use them knows what they do (and that may even
include yourself, if you pick up some of your own Python code years later!).


While it’s not exactly a method, Python provides the document string (called docstring) feature, which
allows you to embed strings inside classes, functions, and methods to help document the code. You
enclose the docstring in triple quotes to identify it in the class, function, or method definition. Also,
the docstring must be the first item in the definition.


Here’s an example of documenting the Product class:


Click here to view code image


class Product:
"""The Product class creates an instance of a product with three
attributes – the product description, price, and inventory"""

To see the docstring for a class, just reference the special doc attribute, as shown here:


Click here to view code image


>>> prod7 = Product()
>>> prod7.__doc__
Free download pdf