Main.Interfaces History
Hide minor edits - Show changes to markup
April 14, 2010, at 01:35 PM MST
by -
Added lines 1-45:
(:source lang=python:)
"""Inheritance in python - interfaces """
- An interface is the set of methods that a class provides.
- Many programming languages provide formal ways for a superclass to enforce
- an interface that any subclass needs to provide.
- Python doesn't provide such a mechanism, but below you will find an example
- that shows how a base class can provide a set of "recommended" methods
- for a subclass to provide.
- Our Shape class does that by defining method "stubs" that raise an exception
- if an implementation is not provided in a subclass.
- 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:)
