Created
January 17, 2015 00:18
-
-
Save thorsummoner/135c6a3c9b02b63c2e79 to your computer and use it in GitHub Desktop.
Overloading the modulo operator to calculate percent.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from percent import Percent | |
from pprint import pprint | |
def main(): | |
pprint( | |
# Ten Percent | |
Percent(5) % 50 | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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