Книга: Fedora™ Unleashed, 2008 edition

Constructors and Destructors

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 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 = name
fluffy = 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 course, ask for as many constructor parameters as you want, although it is usually better to ask for only the ones you need and have other functions 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, you can show the life cycle of an object by printing messages when it is created and deleted:

class dog(object):
 def __init__(self, name):
  self.name = name print
  self.name + " is alive!"
 def __del__(self):
  print self.name + " 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.

Оглавление книги


Генерация: 2.142. Запросов К БД/Cache: 3 / 1
поделиться
Вверх Вниз