提示信息

Python __repr__

开了 已关注

In Python, the __repr__ method is a special method used to provide a string representation of an object. It is typically used for debugging and displaying information about the object in a concise and human-readable format.

The __repr__ method should return a string that is a valid Python expression that could be used to recreate the object. It is often used in combination with the __str__ method, which is used to provide a more user-friendly string representation of the object.

Here is an example of a class that defines the __repr__ method:

  1. class Point:
  2. def __init__(self, x, y):
  3. self.x = x
  4. self.y = y
  5. def __repr__(self):
  6. return f"Point({self.x}, {self.y})"
  7. point = Point(3, 4)
  8. print(point) # Output: Point(3, 4)

In this example, the __repr__ method returns a string that represents the Point object with its x and y coordinates.

It is important to note that the __repr__ method should always return a string that accurately represents the object. The __str__ method, on the other hand, allows for a more customized and user-friendly representation of the object.

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
开了 关注 已关注

最近一次登录:2023-10-09 16:05:04   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图