How to properly implement/overload “__repr__ ”?

前端 未结 3 1428
我在风中等你
我在风中等你 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:31

    __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.

    0 讨论(0)
  • 2021-01-26 00:42

    You should return a string type, for example in Deck:

    def __repr__(self):
        ...
        return 'Deck : '+str(self._deck)
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题