├── README.md ├── points.py └── shapes.py /README.md: -------------------------------------------------------------------------------- 1 | # Classes in Python 2 | Code associated with my tutorial "Everything you need to know about classes in Python": https://youtu.be/tmY6FEF8f1o 3 | 4 | I think I might add some additional code to these examples, so stay watching this repo!! 5 | -------------------------------------------------------------------------------- /points.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | class Point: 4 | def __init__(self, x,y, color="red", size=10): 5 | self.x = x 6 | self.y = y 7 | self.color = color 8 | self.size = size 9 | 10 | def __add__(self, other): 11 | if isinstance(other, Point): 12 | x = self.x + other.x 13 | y = self.y + other.y 14 | return Point(x,y) 15 | else: 16 | x = self.x + other 17 | y = self.y + other 18 | return Point(x,y) 19 | 20 | def plot(self): 21 | plt.scatter(self.x, self.y, c=self.color, s=self.size) 22 | 23 | if __name__ == "__main__": 24 | a = Point(1,3) 25 | b = Point(2,4) 26 | c = a + b 27 | c.plot() 28 | plt.show() -------------------------------------------------------------------------------- /shapes.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | class Polygon: 4 | def __init__(self, sides, name, size=100, color="black", line_thickness=3): 5 | self.sides = sides 6 | self.name = name 7 | self.size = size 8 | self.color = color 9 | self.line_thickness = line_thickness 10 | self.interior_angles = (self.sides-2)*180 11 | self.angle = self.interior_angles/self.sides 12 | 13 | def draw(self): 14 | turtle.color(self.color) 15 | turtle.pensize(self.line_thickness) 16 | for i in range(self.sides): 17 | turtle.forward(self.size) 18 | turtle.right(180-self.angle) 19 | 20 | class Square(Polygon): 21 | def __init__(self, size=100, color="black", line_thickness=3): 22 | super().__init__(4, "Square", size, color, line_thickness) 23 | 24 | def draw(self): 25 | turtle.begin_fill() 26 | super().draw() 27 | turtle.end_fill() 28 | 29 | if __name__ == "__main__": 30 | square = Square(size=300, color="#abcdef") 31 | square.draw() 32 | turtle.done() --------------------------------------------------------------------------------