So I have this code for an object. That object being a move you can make in a game of rock papers scissor. Now, the object needs to be both an integer (for matching a protocol) and a string for convenience of writing and viewing.
class Move:
def __init__(self, setMove):
self.numToName = {0:"rock", 1:"paper",2:"scissors"}
self.nameToNum = dict(reversed(pairing) for pairing in self.numToName.items())
if setMove in self.numToName.keys():
self.mMove=setMove
else:
self.mMove=self.nameToNum.get(setMove) #make it to a number
def defeats(self):
return Move((self.mMove-1)%3)
def losesTo(self):
return Move((self.mMove+1)%3)
def tiesWith(self):
return self
#Operator overloading
def __eq__(A,B):
return A.mMove==B.mMove
def __gt__(A,B):
return A.defeats(B)
def __lt__(A,B):
return A.losesTo(B)
def __ge__(A,B):
return A>B or A==B
def __le__(A,B):
return A<B or A==B
def __str__(self):
return self.numToName.get(self.mMove);
def __int__(self):
return self.mMove;
Now I'm kinda new to python, coming from a C and Java background. A big thing in python is that there is only one correct way to do something. Another thing is not worrying about type. I'm pretty explicitly worrying about type here.
So I'm not sure what the correct way to handle these objects is. At the moment I have an object which an be one of any 3 types (or more but I'm not sure what that would do) Maybe instead I should be used the objects of different classes? and make them singletons? Also my object are currently modifiable after creation, which is a bad thing in my mind.
So is this code Pythonic, and how can i make it more elegant? (I figure this is a good example to use, to help me work out what makes good python code. Sorry if it seems a bit open ended)