-
-
Save sooop/ecf4df125e3d6b7f6887459013bea558 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SaltWater: | |
@classmethod | |
def make(cls, density, weight): | |
s = weight * density | |
w = weight - s | |
return SaltWater(s, w) | |
def __init__(self, s, w): | |
self.w = w | |
self.s = s | |
def __repr__(self): | |
return f'{self.density * 100:.01f}%, {self.weight:.0f}g' | |
@property | |
def density(self): | |
return self.s / self.weight | |
@property | |
def weight(self): | |
return self.s + self.w | |
def addWater(self, w): | |
self.w += w | |
def addSalt(self, s): | |
self.s += s | |
def addSaltWater(self, sw): | |
if not isinstance(sw, SaltWater): | |
raise ValueError() | |
self.s += sw.s | |
self.w += sw.w | |
def __add__(self, sw): | |
if not isinstance(sw, SaltWater): | |
raise ValueError() | |
s = self.s + sw.s | |
w = self.w + sw.w | |
return SaltWater(s, w) | |
def __radd__(self, sw): | |
return self.__ad__(sw) | |
a = SaltWater.make(0.1, 400) | |
b = SaltWater.make(.16, 800) | |
print(a) | |
print(b) | |
c = a + b | |
print(c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment