Skip to content

Commit

Permalink
example code
Browse files Browse the repository at this point in the history
  • Loading branch information
bast committed Sep 12, 2024
1 parent ecf074c commit 3001a13
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
21 changes: 21 additions & 0 deletions content/refactoring/as-class.py
Original file line number Diff line number Diff line change
@@ -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()}")
19 changes: 19 additions & 0 deletions content/refactoring/as-dataclass.py
Original file line number Diff line number Diff line change
@@ -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()}")
12 changes: 12 additions & 0 deletions content/refactoring/using-dict.py
Original file line number Diff line number Diff line change
@@ -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'])}")

0 comments on commit 3001a13

Please sign in to comment.