From 3001a13df7a47c6628fa32439208d89e08e777a7 Mon Sep 17 00:00:00 2001 From: Radovan Bast Date: Thu, 12 Sep 2024 18:57:17 +0200 Subject: [PATCH] example code --- content/refactoring/as-class.py | 21 +++++++++++++++++++++ content/refactoring/as-dataclass.py | 19 +++++++++++++++++++ content/refactoring/using-dict.py | 12 ++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 content/refactoring/as-class.py create mode 100644 content/refactoring/as-dataclass.py create mode 100644 content/refactoring/using-dict.py diff --git a/content/refactoring/as-class.py b/content/refactoring/as-class.py new file mode 100644 index 0000000..0809aac --- /dev/null +++ b/content/refactoring/as-class.py @@ -0,0 +1,21 @@ +import math + + +class Moon: + def __init__(self, name, radius, contains_water=False): + self.name = name + self.radius = radius # in kilometers + self.contains_water = contains_water + + def surface_area(self) -> float: + """Calculate the surface area of the moon assuming a spherical shape.""" + return 4.0 * math.pi * self.radius**2 + + def __repr__(self): + return f"Moon(name={self.name!r}, radius={self.radius}, contains_water={self.contains_water})" + + +europa = Moon(name="Europa", radius=1560.8, contains_water=True) + +print(europa) +print(f"Surface area (km^2) of {europa.name}: {europa.surface_area()}") diff --git a/content/refactoring/as-dataclass.py b/content/refactoring/as-dataclass.py new file mode 100644 index 0000000..88c7137 --- /dev/null +++ b/content/refactoring/as-dataclass.py @@ -0,0 +1,19 @@ +from dataclasses import dataclass +import math + + +@dataclass +class Moon: + name: str + radius: float # in kilometers + contains_water: bool = False + + def surface_area(self) -> float: + """Calculate the surface area of the moon assuming a spherical shape.""" + return 4.0 * math.pi * self.radius**2 + + +europa = Moon(name="Europa", radius=1560.8, contains_water=True) + +print(europa) +print(f"Surface area (km^2) of {europa.name}: {europa.surface_area()}") diff --git a/content/refactoring/using-dict.py b/content/refactoring/using-dict.py new file mode 100644 index 0000000..32eb895 --- /dev/null +++ b/content/refactoring/using-dict.py @@ -0,0 +1,12 @@ +import math + + +def surface_area(radius: float) -> float: + return 4.0 * math.pi * radius**2 + + +europa = {"name": "Europa", "radius": 1560.8, "contains_water": True} + + +print(europa) +print(f"Surface area (km^2) of {europa['name']}: {surface_area(europa['radius'])}")