Skip to content

Instantly share code, notes, and snippets.

@mocquin
Last active June 27, 2021 17:19
Show Gist options
  • Save mocquin/6f67926334fa1745792f0ec255561c1d to your computer and use it in GitHub Desktop.
Save mocquin/6f67926334fa1745792f0ec255561c1d to your computer and use it in GitHub Desktop.
import numpy as np
class Physical():
def __init__(self, value, unit=""):
self.value = value
self.unit = unit
def __repr__(self):
return f"<Physical:({self.value}, {self.unit})"
def __str__(self):
return f"{self.value} {self.unit}"
def __add__(self, other):
if self.unit == other.unit:
return Physical(self.value + other.value, self.unit)
else:
raise ValueError("Physical objects must have same unit to be added.")
def __sub__(self, other):
if self.unit == other.unit:
return Physical(self.value - other.value, self.unit)
else:
raise ValueError("Physical objects must have same unit to be subtracted.")
def __mul__(self, other):
return Physical(self.value * other.value, f"{self.unit}*{other.unit}")
def __truediv__(self, other):
return Physical(self.value / other.value, f"{self.unit}/{other.unit}")
def __pow__(self, powfac):
return Physical(self.value**powfac, f"{self.unit}^{powfac}")
weights = Physical(np.array([55.6, 45.7, 80.3]), "kilogram")
heights = Physical(np.array([1.64, 1.85, 1.77]), "meter")
print(weights) # [55.6 45.7 80.3] kilogram
print(heights) # [1.64 1.85 1.77] meter
print(heights + heights) # [3.28 3.7 3.54] meter
# print(height + weights) # raises ValueError
print(heights**2) # [2.6896 3.4225 3.1329] meter^2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment