Object-Oriented Programming With Python (part 2) - Chaos And Destruction
(Page 5 of 5 )
In Python, an object is automatically destroyed once the references to it are no longer in use, or when the Python script completes execution. A destructor is a special function which allows you to execute commands immediately prior to the destruction of an object.
You do not usually need to define a destructor - but if you want to see what it looks like, take a look at this:
class veryBigSnake:
# constructor
# now accepts name and type as arguments
def __init__(self, name="Peter Python", type="python"):
self.name = name
self.type = type
print "New snake in da house!"
# function to set snake name
def set_snake_name(self, name):
self.name = name
# function to set snake type
def set_snake_type(self, type):
self.type = type
# function to display name and type
def who_am_i(self):
print "My name is " + self.name + ", I'm a " + self.type + " and I'm
perfect for you! Take me home today!"
# destructor
def __del__(self):
print "Just killed the snake named " + self.name + "!"
Note that a destructor must always be called
__del__()
Here's a demonstration of how to use it:
>>> alpha = veryBigSnake("Bobby Boa", "boa constrictor")
New snake in da house!
>>> beta = veryBigSnake("Alan Adder", "harmless green adder")
New snake in da house!
>>> del beta
Just killed the snake named Alan Adder!
>>> del alpha
Just killed the snake named Bobby Boa!
>>>
And with multiple murder on my hands, it's now time to bid
you goodbye. If you're interested in the more arcane aspects of Python's OO capabilities - operator overloading, private and public variables, and so on - you should consider visiting the following sites:
The official Python tutorial, at
http://www.python.org/doc/current/tut/node11.htmlThe Python Cookbook, at
http://aspn.activestate.com/ASPN/Cookbook/PythonThe Vaults of Parnassus, at
http://www.vex.net/parnassus/Python HOWTOs, at
http://py-howto.sourceforge.net/The Python FAQ, at
http://www.python.org/doc/FAQ.htmlUntil next time...stay healthy!
Note: All examples in this article have been tested on Linux/i586 with Python 1.5.2. Examples are illustrative only, and are not meant for a production environment. YMMV!\n
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |