首页 > 编程语言 > 详细

python笔记34-类里面的__str__ 和__unicode__作用

时间:2019-01-31 15:16:50      阅读:129      评论:0      收藏:0      [点我收藏+]

前言

最近学django,看到不少教程里面models.py里面建表,写一个类的时候,习惯上加个__str__ ,开始不太明白,简单的实践后才知道是为了美化类实例的打印内容。
python3 里面用__str__ ,python2里面用__unicode__

写个类

先写个简单的类,实例化后打印实例的结果

class Person():
    def __init__(self):
        self.name = "张三"

if __name__ == '__main__':
    a = Person()
    print(a)

打印结果:<main.Person object at 0x0000000001E79828>

这个实例化后的结果显示.Person object 显示的内容看不懂,为了美化输出,可以加个__str__方法

__str__作用

class Person():
    def __init__(self):
        self.name = "张三"

    def __str__(self):
        return self.name

if __name__ == '__main__':
    a = Person()
    print(a)

打印结果:张三

**备注:python3 里面用__str__ ,python2里面用__unicode__**

python笔记34-类里面的__str__ 和__unicode__作用

原文:https://www.cnblogs.com/yoyoketang/p/10342017.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!