From c498ca8a8e284092a6cdab0ae972b7cd0637e52f Mon Sep 17 00:00:00 2001 From: waldek Date: Wed, 10 Nov 2021 14:57:09 +0100 Subject: [PATCH] adds shapes --- learning_python3.md | 71 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 69 insertions(+), 2 deletions(-) diff --git a/learning_python3.md b/learning_python3.md index 6c9c821..3bd4f99 100644 --- a/learning_python3.md +++ b/learning_python3.md @@ -886,6 +886,7 @@ def pretty_print(msg, decorator="#"): print("{} {} {}".format(decorator, msg, decorator)) print(decorator * line_len) + pretty_print("Wouter") pretty_print("Python rules!") pretty_print("Alice", "-") @@ -1939,6 +1940,7 @@ class Animal(object): else: print("{} growls in {}'s face".format(self.name, person)) + dog_1 = Animal("bobby", 4, "dave") dog_2 = Animal("dianne", 4, "alice") dog_3 = Animal("rex", 3, "dave") @@ -2041,11 +2043,76 @@ for animal in all_animals: 🏃 Try it --- -Take the additional class yyou made, such as vehicle and do some inheritance. +Take the additional class you made, such as vehicle and do some inheritance. For vehicles you could create a base class with a brand and number of wheels and seats. Then inherit for a bus, bike, car, cycle, etc. -**TODO shapes and surfaces** +## A *practical* example + +```python +import math + + +class Shape(object): + def __init__(self): + self.area = 0 + + def __str__(self): + return "I'm a {} with an area of {:.2f} cm2".format( + self.__class__.__name__, + self.area, + ) + + def __add__(self, other): + combi_shape = Shape() + combi_shape.area = self.area + other.area + return combi_shape + + def __sub__(self, other): + combi_shape = Shape() + combi_shape.area = self.area - other.area + return combi_shape + + def __div__(self, value): + combi_shape = Shape() + combi_shape.area = self.area / value + return combi_shape + + +class Square(Shape): + def __init__(self, width): + Shape.__init__(self) + self.area = width * width + + +class Rectangle(Shape): + def __init__(self, width, height): + Shape.__init__(self) + self.area = width * height + + +class Triangle(Shape): + def __init__(self, base, height): + Shape.__init__(self) + self.area = (self.width * self.height) / 2 + + +class Circle(Shape): + def __init__(self, radius): + Shape.__init__(self) + self.area = math.pi * math.pow(radius, 2) + + +if __name__ == "__main__": + t = Square(4) + r = Rectangle(4, 6) + c = Circle(1.6) + print(t) + print(r) + print(c) + combi = t + r - c + print(combi) +``` ## Now some *practical* improvements