为自己定义每个python类添加__repr__和__str__

在类定义里,使用__str____repr__双下划线能够自行控制类中的字符串转换.

代码示例

class Car:
    def __init__(self,color,mileage):
        self.color = color
        self.mileage = mileage

    def __repr__(self):
        return (f'{self.__class__.__name__}('
                f'{self.color!r},{self.mileage!r})')

    def __str__(self):
        return f'a {self.color} car'


my_car = Car('blue',929192)
print(my_car)   
#=> a blue car
#=> 如果不定义__str__,则结果为 Car('blue',929192)
  • __str__ 的结果应该是可读的.

  • __repr__ 的结果应该是无歧义的,方便开发人员调试.

  • 如果没有定义__str__ , 则会默认调用__repr__


Flutter 写的app, 需要源码可以私信~~


最好的笔记软件

上一篇:PostgreSQL12安装(二)


下一篇:python面向对象编程的基本概念