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)
To me, the concept of code being “pythonic” really comes down to the idea that once you understand what problem you’re trying to solve, the code almost writes itself. In this case, without worrying about the deeper abstractions of players, games, throws, etc., you have the following problem: there are a certain number of types of moves, each with a name, with set rules for which moves beat which other moves, and you need to find a way to define moves and figure out which move wins in a comparison.
When I read your code, I don’t immediately see this problem, I see a lot of extra thought that went into the code itself, finding type representations, doing arithmetic tricks, and generally forcing the problem into a code framework, rather than the other way around. So I’d suggest something like:
And you’re done. You can throw in all the other accessors, etc. but it’s really just icing, the core problem is solved and the code is readable, flexible, easy to extend, etc. That’s really what I think “pythonic” means.