Last active
February 21, 2017 11:28
-
-
Save shredding/446605205e26319066e0268447122277 to your computer and use it in GitHub Desktop.
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 Selection(): | |
OPTIONS = ('paper', 'scissor', 'rock') | |
def __init__(self, selection): | |
if selection not in self.OPTIONS: | |
raise ValueError('selection must be one of {}.'.format(', '.join(self.OPTIONS))) | |
self.selection = selection | |
def __eq__(self, other): | |
""" | |
The == operator. | |
Two selections are equal if their selections are equal. | |
""" | |
return self.selection == other.selection | |
def __ne__(self, other): | |
""" | |
The != operator. | |
That's simply the opposite of the == operator. | |
""" | |
return not self.__eq__(other) | |
def __gt__(self, other): | |
""" | |
The > operator. | |
We'll implement the actual game logic here. | |
""" | |
if self.selection == 'paper': | |
return True if other.selection == 'rock' else False | |
if self.selection == 'scissor': | |
return True if other.selection == 'paper' else False | |
if self.selection == 'rock': | |
return True if other.selection == 'scissor' else False | |
def __ge__(self, other): | |
""" | |
The >= operator. | |
From now on we are building up on the __ge__ and __eq__ operator. | |
""" | |
return self.__gt__(other) or self.__eq__(other) | |
def __lt__(self, other): | |
""" | |
The < operator. | |
""" | |
return not self.__ge__(other) | |
def __le__(self, other): | |
""" | |
The <= operator. | |
""" | |
return self.__lt__(other) or self.__eq__(other) | |
def __str__(self): | |
""" | |
Here's another cool magic function. It defines what's returned | |
when something is calling the str() method on our class. | |
Since it's mainly a wrapper for a string, let's return that | |
string instead of the not-that-descriptive class-instance-version. | |
Hint: The .format() method is calling str() on all passed values. | |
""" | |
return self.selection |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment