__
repr__
在python中的用法
__repr__
方法在 Python 中是一个非常重要的魔术方法(magic method),它用于返回一个对象的“官方”字符串表示。这个方法的主要目的是提供一个对象的“标准”字符串表示,通常用于调试和开发。当你试图将一个对象转换成字符串(例如使用 print
函数),或者在交互式解释器中直接显示对象时,Python 会调用这个对象的 __repr__
方法。
如果仅使用__
string__
的话,下面的代码直接打印对象会出现全类名和地址,加上__repr__
就可以直接打印出更加清晰的对象信息
class Person:
def __init__(self, name, age, job):
self.name = name
self.age = age
self.job = job
def __str__(self):
return f"{self.name} {self.age} {self.job}"
def bubble_sort(list):
for i in range(0, len(list) - 1):
for j in range(0, len(list) - i - 1):
if list[j].age > list[j + 1].age:
list[j],list[j + 1] = list[j + 1], list[j]
people = [Person("fds1", 27, "developer1"), Person("fdp1", 22, "developer2"), Person("fdb1", 21, "developer3"),
Person("fdd1", 25, "developer4")]
bubble_sort(people)
print(people) # [<__main__.Person object at 0x1030facd0>, <__main__.Person object at 0x1030fad90>, <__main__.Person object at 0x1030fac70>, <__main__.Person object at 0x1030fae50>]
修改后:
class Person:
def __init__(self, name, age, job):
self.name = name
self.age = age
self.job = job
def __str__(self):
return f"{self.name} {self.age} {self.job}"
def __repr__(self):
return self.__str__()
def bubble_sort(list):
for i in range(0, len(list) - 1):
for j in range(0, len(list) - i - 1):
if list[j].age > list[j + 1].age:
list[j],list[j + 1] = list[j + 1], list[j]
people = [Person("fds1", 27, "developer1"), Person("fdp1", 22, "developer2"), Person("fdb1", 21, "developer3"),
Person("fdd1", 25, "developer4")]
bubble_sort(people)
print(people) # [fdb1 21 developer3, fdp1 22 developer2, fdd1 25 developer4, fds1 27 developer1]