By default, Python gives you all the methods the parent class has, but you can override
that by providing new implementations for the classes that need them. For example:
class modelt(car):
def setColor(self, color):
print “Sorry, Model Ts only come in black!”
myford = ford()
mycar = modelt()
The first car is created as a Ford, so setColor() will work fine because it uses the method
from the
car class. However, the second car is created as a Model T, which has its own
setColor() method, so the call will fail.
This provides an interesting scenario: What do you do if you have overridden a method
and yet want to call the parent’s method also? If, for example, changing the color of a
Model T was allowed but just cost extra, we would want to print a message saying, “You
owe $50 more,” but then change the color. To do this, we need to use the class object
from which our current class is inherited—
car in this example. Here’s an example:
class modelt(car):
def setColor(self, color):
print “You owe $50 more”
car.setColor(self, color)
mycar = modelt()
print mycar.color
That prints the message and then changes the color of the car.
The Standard Library and the Vaults of Parnassus
A default Python install includes many modules (blocks of code) that enable you to inter-
act with the operating system, open and manipulate files, parse command-line options,
perform data hashing and encryption, and much more. This is one of the reasons most
commonly cited when people are asked why they like Python so much—it comes stocked
to the gills with functionality you can take advantage of immediately. In fact, the number
of modules included in the Standard Library is so high that entire books have been
written about them—try Python Standard Library (O’Reilly, ISBN: 0-596-00096-0) for a
comprehensive, if slightly dated, list of them.
For unofficial scripts and add-ons for Python, the recommended starting place is called
the Vaults of Parnassus: There you can find about 20,000 public scripts
and code examples for everything from mathematics to games.
Object Orientation

Get Ubuntu Unleashed, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.