How to properly implement/overload “__repr__ ”?

前端 未结 3 1427
我在风中等你
我在风中等你 2021-01-26 00:27

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

3条回答
  •  鱼传尺愫
    2021-01-26 00:55

    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
    

提交回复
热议问题