I'm trying to learn Python, so I started with a program to convert length units, mixing imperial and metric. First I wrote a bunch of small simple functions, but then I wanted to solve the issue of having an intuitive way of calling one function with some easy to remember parameter values in order to convert from any unit to any other unit, as opposed to having to call a bunch of different function names.
Does each instance of Convert remain in memory when I am using __new__
and not actually returning an instance of the class? For example, since only a float is stored in 'x' at the end, is the instance of convert that was created destroyed?
Is this approach valid overall? It feels like I've done something a little strange here.
Note: The code works on both Python 3 and 2.
class Convert(object):
def __new__(self, val, unit_in, unit_out):
convertString = '%s_to_%s' % (unit_in, unit_out)
try:
convertFunction = getattr(self, convertString)
except:
return None
return convertFunction(self, val)
def mm_to_cm(self, millimeters):
return millimeters / 10.0
def mm_to_in(self, millimeters):
return ((millimeters / 1000.0) / 0.9144) * 36.0
def mm_to_ft(self, millimeters):
return ((millimeters / 1000.0) / 0.9144) * 3.0
def mm_to_m(self, millimeters):
return millimeters / 1000.0
def cm_to_mm(self, centimeters):
return centimeters * 10.0
def cm_to_in(self, centimeters):
return ((centimeters / 100.0) / 0.9144) * 36.0
def cm_to_ft(self, centimeters):
return ((centimeters / 100.0) / 0.9144) * 3.0
def cm_to_m(self, centimeters):
return centimeters / 100.0
def in_to_mm(self, inches):
return (((inches / 12.0) / 3.0) / (1.0 / 0.9144)) * 1000.0
def in_to_cm(self, inches):
return (((inches / 12.0) / 3.0) / (1.0 / 0.9144)) * 100.0
def in_to_ft(self, inches):
return inches / 12.0
def in_to_m(self, inches):
return (((inches / 12.0) / 3.0) / (1.0 / 0.9144))
def ft_to_mm(self, feet):
return (feet / 3.0) / (1.0 / 0.9144) * 1000.0
def ft_to_cm(self, feet):
return (feet / 3.0) / (1.0 / 0.9144) * 100.0
def ft_to_in(self, feet):
return feet * 12.0
def ft_to_m(self, feet):
return (feet / 3.0) / (1.0 / 0.9144)
def m_to_mm(self, meters):
return meters * 1000.0
def m_to_cm(self, meters):
return meters * 100.0
def m_to_in(self, meters):
return (meters / 0.9144) * 36.0
def m_to_ft(self, meters):
return (meters / 0.9144) * 3.0
print(Convert( 1.0, 'ft', 'in'))
print(Convert(12.0, 'in', 'ft'))
print(Convert( 0.3048, 'm', 'ft'))
x = Convert(3, 'ft', 'm')
print(x)
exit()
output:
12.0
1.0
1.0
0.9144