New to python and this might be a silly question, but how does one properly implement the repr method?
I wrote a quick little program to simulate a game of card
__repr__
ideally could return the representation of the object that you would use to create this instance.
From repr():
For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object.
You should return a string type, for example in Deck:
def __repr__(self):
...
return 'Deck : '+str(self._deck)
First, It should be noted that you don't have to implement the __repr__
method. Python provides a somewhat reasonable default (it'll at least tell you the type).
If you want to implement __repr__
, the "rule of thumb" is that where it makes sense, you should provide enough information about the object that a user could reconstruct it. In your case, there doesn't seem to be any real difference from one deck to another, so
def __repr__(self):
return 'Deck()'
might be a reasonable return value. This doesn't get the state right (after shuffling), but you don't provide an interface for constructing a deck in a particular state. If you did, it might look like:
def __repr__(self):
return 'Deck(%s)' % self._deck