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):    def __init__(self, name):        self.name = namefluffy = Dog("Fluffy")print fluffy.name

If you do not provide a name parameter when creating the Dog object, Python reports an error and stops. You can, of ...

Get Ubuntu Unleashed 2013 Edition: Covering 12.10 and 13.04, Eighth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.