Constructors and Destructors

To help you automate the creation and deletion of objects, you can easily override two default methods:_init_and_del_. These are the methods called by Python when a class is being instantiated and freed, known as the constructor and destructor, respectively.

Having a custom constructor is great for when you need to accept a set of parameters for each object being created. For example, you might want each dog to have its own name on creation, and you could implement that with this code:

class dog(object): = name fluffy = dog("Fluffy") print

If you do not provide a name parameter when creating the dog object, Python reports an error and stops. You can, of course, ask for as many constructor parameters as you want, although it is usually better to ask only for the ones you need and have other functions to fill in the rest.

On the other side of things is the destructor method, which allows you to have more control over what happens when an object is destroyed. Using the two, we can show the life cycle of an object by printing messages when it is created and deleted:

class dog(object): = name print + " is alive!"

print + " is no more!" fluffy = dog("Fluffy")

The destructor is there to give you the chance to free up resources allocated to the object or perhaps log something to a file.

Was this article helpful?

0 0

Post a comment