当前位置: 首页 > 后端技术 > Python

为您定义的每个python类添加__repr__和__str__

时间:2023-03-26 15:49:23 Python

在类定义中,使用__str__和__repr__双下划线来控制类中的字符串转换。代码示例classCar:def__init__(self,color,mileage):self.color=colorself.mileage=mileagedef__repr__(self):return(f'{self.__class__.__name__}('f'{self.color!r},{self.mileage!r})')def__str__(self):returnf'a{self.color}car'my_car=Car('blue',929192)print(my_car)#=>蓝色car#=>if_isnotdefined_str__,theresultisCar('blue',929192)__str__的结果应该是可读的。__repr__的结果应该没有歧义,方便开发者调试。如果没有定义__str__,app默认会调用Flutter写的__repr__,需要源码的可以私信~~简繁火星字体转换哄女朋友神器号衡量好坏电视程序直播表最好用的笔记软件