__repr__在python中的巧妙用法

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值