#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @file: shape.py @author: rachlin @description: Demonstrate the fundamentals of creating objects with attributes and methods """ import math import matplotlib.pyplot as plt class Circle: def __init__(self, name, radius, x=0, y=0, color='black'): """ Object constructor for the Circle class """ self.name = name self.radius = radius self.x = x self.y = y self.color = color def move(self, dx, dy): """ Move the location of the shape by some delta """ self.x += dx self.y += dy def area(self): """ Area of this circle """ return math.pi * self.radius ** 2 def circumference(self): """ Circumference of this circle """ return 2 * math.pi * self.radius def __str__(self): """ Render this circle as a string """ return "Circle ("+self.name+") with radius=" + str(self.radius) class Square: def __init__(self, name, side, x=0, y=0, color='black'): """ Object constructor for the Circle class """ self.name = name self.side = side self.x = 0 self.y = 0 self.color = color def move(self, dx, dy): """ Move the location of the shape by some delta """ self.x += dx self.y += dy def area(self): """ Area of a square """ return self.side ** 2 def perimeter(self): """ Perimeter of a square """ return 4 * self.side def __str__(self): """ Render a square as a string for printing """ return "Square ("+self.name+") with side=" + str(self.side) def draw(shapes): plt.figure(figsize=(3,3), dpi=150) plt.grid() plt.xlim(0,10) plt.ylim(0,10) for shape in shapes: if type(shape) == Circle: marker = 'o' else: marker = 's' plt.scatter(shape.x, shape.y, marker=marker, color=shape.color) plt.text(shape.x+.2, shape.y+.2, shape.name) plt.show() def main(): # Create a circle c1 = Circle("A", 20, color='red') print("c1:", c1) print("Area of c1:", c1.area()) print("Current position: ", c1.x, c1.y) c1.move(2, 4) c1.move(1, -1.5) print("New position: ", c1.x, c1.y) # Create another circle c2 = Circle("B", 40, 6,8, color='blue') # Now a square s1 = Square("X", 5, color = 'green') s1.move(4,5) print("Area of s1:", s1.area()) #print("Circumference of s1:", s1.circumference()) # ERROR # Draw a list of shapes draw([c1, c2, s1]) # Move the shapes and draw again s1.move(0,1) c1.move(-1,-1) c2.move(1,-1) draw([c1, c2, s1]) if __name__ == '__main__': main()