With this code I want to build a new Energy
class that makes use of the existing mathematical operations (data model methods) in the build in float
class.
class Energy(float):
def __init__(self, value, unit="J"):
super().__init__(value)
# dict of possible energy input units
self.units= {
"J" : 1.0,
"kJ": 10**-3,
"kcal" : 1/(4.1868) * 10**-3
}
# check wich unit is used and calculate the value into 'J'
for e in self.units.keys():
if e == unit:
self = value * self.units[e]
def kJ(self):
return self * self.unit["kJ"]
def kcal(self):
return self * self.unit["kcal"]
def __str__(self):
return str(float(self)) + " J"
e = Energy(10, "kJ")
print(e)
This can't be achieved, so I followed the suggested solution by Tim Roberts. This means to implement all of the data model methods like __add__()
etc. by your self.