Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Usage:
- #
- #converter = UnitConvert()
- #result = converter.convert(Numerical value, current unit, wanted unit)
- #
- #Result will be a string, e.g. 576.3g
- class UnitConvert:
- allowedMass = ['g','kg']
- allowedForce = ['N']
- gravity = 9.8
- conversion = ""
- #For now I am just bastardizing this.
- #Eventually pretty code and awesome conversions will happen.
- def convert(self, amount, uFrom, uTo):
- #Store given information
- self.uFrom = uFrom
- self.uTo = uTo
- #a is amount. not in untis
- self.amount = amount
- #Identify Units
- self.identifyConversionType()
- #Call proper conversion
- if self.conversion == "mm":
- self.convertMassToMass()
- elif self.conversion == "mf":
- self.convertMassToForce()
- elif selfconversion == "fm":
- self.convertForceToMass()
- #Return result as a string to the requesting function
- self.conversion = ""
- return self.result
- def identifyConversionType(self):
- #Identify the incoming unit type
- for i in self.allowedMass:
- if self.uFrom == i:
- self.conversion += "m"
- else:
- for i in self.allowedForce:
- if self.uFrom == i:
- self.conversion += "f"
- #Identify the outgoing unit type
- for i in self.allowedMass:
- if self.uTo == i:
- self.conversion += "m"
- else:
- for i in self.allowedForce:
- if self.uTo == i:
- self.conversion += "f"
- def convertMassToMass(self):
- #First convert from whatever unit to SI unit
- self.convertMassToSIMass(self.uFrom)
- #Then from the SI unit to the resultant unit
- self.convertMassFromSIMass(self.uTo)
- #Generate a string of the result
- self.result = str(self.amount) + self.uTo
- def convertMassToForce(self):
- #Force = Mass * Acceleration
- self.amount = self.convertMassToSIMass(self.uFrom) * self.gravity
- #Generate resultant string
- self.result = str(self.amount) + self.uTo
- def convertForceToMass(self):
- #Mass = Force / gravity
- self.amount = self.amount / self.gravity
- #Convert the kg to outgoing unti
- self.convertMassFromSIMass(self.uTo)
- #Generate resultant string
- self.result = str(self.amount) + self.uTo
- def convertMassToSIMass(self, unit):
- if unit == 'g':
- return self.amount * 0.001
- elif unit == 'kg':
- return self.amount
- def convertMassFromSIMass(self, unit):
- if unit == 'kg':
- return self.amount
- if unit == 'g':
- return self.amount * 1000
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement