Skip to content

Instantly share code, notes, and snippets.

@thorsummoner
Created January 17, 2015 00:18
Show Gist options
  • Save thorsummoner/135c6a3c9b02b63c2e79 to your computer and use it in GitHub Desktop.
Save thorsummoner/135c6a3c9b02b63c2e79 to your computer and use it in GitHub Desktop.
Overloading the modulo operator to calculate percent.
from percent import Percent
from pprint import pprint
def main():
pprint(
# Ten Percent
Percent(5) % 50
)
class Percent(float):
"""
Redefine the `%` operator, such that I can be used to represent:
`X % Y`
as a way to calculate the percentage:
`X / Y * 100.0`
Use like `my_percentage = Percent(X) % Y`
"""
def __mod__(self, other):
"""Override the modulo operator with a percentage calculation."""
return self / other * 100.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment