5

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

 3 years ago
source link: https://segmentfault.com/a/1190000039855020
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

发布于 10 分钟前

在类定义里,使用__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, 需要源码可以私信~~


最好的笔记软件


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK