Main.Interfaces History

Hide minor edits - Show changes to markup

April 14, 2010, at 01:35 PM MST by 10.84.44.72 -
Added lines 1-45:

(:source lang=python:)

"""Inheritance in python - interfaces """

  1. An interface is the set of methods that a class provides.
  2. Many programming languages provide formal ways for a superclass to enforce
  3. an interface that any subclass needs to provide.
  4. Python doesn't provide such a mechanism, but below you will find an example
  5. that shows how a base class can provide a set of "recommended" methods
  6. for a subclass to provide.
  7. Our Shape class does that by defining method "stubs" that raise an exception
  8. if an implementation is not provided in a subclass.
  9. assume the Point object was defined in a module called shapes_inheritance

from shapes_inheritance import Point

class Shape (object) :

    def __init__(self, x=0, y=0) :
        """creates an instance of a Shape with a location given
        by x and y"""
        self.location = Point(x, y)
    def move(self, x, y) :
        """move a shape object to a location given by x and y"""
        self.location = Point(x, y)
    def distance_to_origin(self) :
        return self.location.distance_to_origin()
    def distance(other) :
        return self.location.distance(other.location)
    def duplicate(self) :
        """returns a duplicate of a shape"""
        raise NotImplemented
    def area(self) :
        """returns the area of a shape"""
        raise NotImplemented
    def perimeter(self) :
        """returns the perimiter of a shape"""
        raise NotImplemented
    def scale(self, s) :
        """rescale the size of a shape by the given amount"""
        raise NotImplemented
    def __repr__(self) :
        return "A shape located at: " + str(self.location)

(:sourceend:)