Tool-Building in Bioinformatics

TBiB Q4/2006

BiRC / Courses / TBiB / Lecture Notes / Derived classes

Derived classes

So far, you haven't seen derived classes in this course. But since you are already familiar with the concept from Java, there isn't much to it in Python. To create a class Square sub-classing class Polygon, you put the superclass, Polygon, in parentheses when defining the subclass, Square:

class Polygon:
    # class definition

class Square(Polygon):
    # class definition

If you need to pass parameters to the super-class constructor, you simply call its __init__ method explicitly:

class Polygon:
    def __init__(self, colour, line_width):
        self.__colour = colour
        self.__line_width = line_width

    # remaining class definition

class Square(Polygon):
    def __init__(self, colour, line_width, line_length):
        Polygon.__init__(self, colour, line_width)
        self.__line_length = line_length

    # remaining class definition

It is a good idea to prefix attributes of objects, such as the colour, line widths, and line length above, with a double underscore (__). Python will manage such names specially, and among other things prevent name-clashes between super- and sub-classes.

For overriding methods, you simply add a method with the same name to the sub-class:

class Polygon:
    ...

    def draw(self):
        # draw polygon

    # remaining class definition

class Square(Polygon):
    ...

    def draw(self):
        # draw square

    # remaining class definition

With this explanation, it should be clear what we are doing with the HTMLParser: we derive a new class, CSSPlanParser, where we override the methods handle_starttag, handle_endtag, and handle_data, to extract the information we need. These three methods are called by the super-class when it encounters start-/end-tags and when it encounters text outside of tags.

You can read more about inheritance in Python in chapter 9 of Python—how to program.