Quantcast
Channel: Give a number units when used through a class - Stack Overflow
Viewing all articles
Browse latest Browse all 5

Answer by Paul92 for Give a number units when used through a class

$
0
0

There are ways of doing it, but firstly you should ask yourself whether you want this. Having different units can get confusing. You can put conversions at the appropriate places (e.g. after reading the input from user) and have your system work solely on a given unit (that's why we have SI units, after all). Being able to support multiple units internally not only complicates the code, but introduces another source of possible confusion.

There are packages which do this for you, such as units, numericalunits or pint.

An example taken from units documentation is:

>>> from units import unit>>> metre = unit('m')>>> second = unit('s')>>> print(metre(10) / second(2))5.00 m / s>>> print(metre(10) ** 3)1000.00 m * m * m

See how metre creates a meter value, and it keeps track of its usage. It has also support for defining custom units.

Therefore, you could simply store the values in your class as values from units or other package, and you're all set. I looked a bit into the code of units and is quite short and I think it's a good source of learning how to handle stuff like this in your own code.


I have to cite the failure of Nasa Mars Climate Orbiter, which was due to a unit discrepancy.


Viewing all articles
Browse latest Browse all 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>