Nuestro conocimiento compartido. Nuestro tesoro compartido. Wikipedia.
TreeWeb::Artículos::Python::Inheritance and POO with Python
Permalink: http://www.treeweb.es/u/1296/ 16/10/2015

Inheritance and POO with Python

#-*- coding: utf-8 -*- u""" Inheritance and POO with Python """ class Coordinates(object): def __init__(self, x=0, y=0): self.x = x self.y = y class Point(Coordinates): def __init__(self, x=0, y=0): super(Point, self).__init__(x,y) def draw(self): print '(%s, %s)' % (self.x, self.y) class Figure(object): # Abstract! figure = 'Figure' def __init__(self): self.coordinates = Coordinates() def draw(self): raise Exception("You should implement `draw` method.") class Line(Figure): figure = 'Line' def __init__(self): self.points = [] # Points def add(self, point): return self.points.append(point) def draw(self): print 'I am a line with %s points:' % len(self.points) for point in self.points: point.draw() class Group(Figure): figure = 'Group' def __init__(self): self.figures = [] # Figures def add(self, figure): return self.figures.append(figure) def draw(self): print 'I am a group with %s figures:' % len(self.figures) for figure in self.figures: figure.draw() if __name__ == '__main__': line1 = Line() line1.add(Point(1,1)) line1.add(Point(1,2)) line2 = Line() line2.add(Point(10,1)) line2.add(Point(20,2)) line2.add(Point(30,3)) group1 = Group() group1.add(line1) group1.add(line2) group1.draw()