Книга: 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.
- Разработка приложений баз данных InterBase на Borland Delphi
- Open Source Insight and Discussion
- Introduction to Microprocessors and Microcontrollers
- Chapter 6. Traversing of tables and chains
- Chapter 8. Saving and restoring large rule-sets
- Chapter 11. Iptables targets and jumps
- Chapter 5 Installing and Configuring VirtualCenter 2.0
- Chapter 16. Commercial products based on Linux, iptables and netfilter
- Appendix A. Detailed explanations of special commands
- Appendix B. Common problems and questions
- Appendix E. Other resources and links
- IP filtering terms and expressions