O'Reilly logo

Ubuntu Unleashed 2013 Edition: Covering 12.10 and 13.04, Eighth Edition by Matthew Helmke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required