HomePython Page 5 - Object-Oriented Programming With Python (part 2)
Chaos And Destruction - Python
With the basics out of the way, this concluding article discussesmore advanced aspects of Python's OO implementation, including inheritance,destructors and overrides.
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:
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