Python object.__repr__(self) should be an expression?

后端 未结 7 1875
名媛妹妹
名媛妹妹 2020-12-22 15:36

I was looking at the builtin object methods in the Python documentation, and I was interested in the documentation for object.__repr__(self). Here\'s what it sa

相关标签:
7条回答
  • 2020-12-22 15:56

    To see how the repr works within a class, run the following code, first with and then without the repr method.

    class Coordinate (object):
        def __init__(self,x,y):
            self.x = x
            self.y = y
    
        def getX(self):
            # Getter method for a Coordinate object's x coordinate.
            # Getter methods are better practice than just accessing an attribute directly
            return self.x
        def getY(self):
    
            # Getter method for a Coordinate object's y coordinate
            return self.y
    
        def __repr__(self):  #remove this and the next line and re-run
            return 'Coordinate(' + str(self.getX()) + ',' + str(self.getY()) + ')' 
    
    >>>c = Coordinate(2,-8)
    >>>print(c)
    
    0 讨论(0)
提交回复
热议问题