python __str__和__unicode__ 作用是什么?有何用?

两则区别:

    __str__()             python2,它返回字节。python3返回的是字符

    __unicode__()    python3中被弃用

__unicode__

    python2 

    用于实现内建的unicode()调用;应该返回一个Unicode对象。当该方法没有定义时,则尝试使用字符串转换,并且将字符串转换的结果,使用系统认的编码转换为Unicode。

    在python2由于兼容性问题,应该将所有的字符串格式化__unicode__(),并创建一个存根__str__()方法

def __str__(self):
    return unicode(self).encode('utf-8')

    python3

    在Python 3 上,因为所有的字段都原生被认为是Unicode,只需使用__str__() 方法(__unicode__() 方法被废弃)

ptyhon2参考资料:http://usyiyi.cn/translate/python_278/reference/datamodel.html#objects-values-and-types

__str__

     在python2中返回的是ASCII字符

     在python3总返回的是unicode字符,因为python3认为unicode类型

代码示例:

class Test:

    def __init__(self, name, job):
        self.name = name
        self.job = job  
		
	def __str__(self):
        return 'Name:' + self.name
        
instance = Test('xiaoming', 'Teacher')
print(instance)

同时兼用python2和python3方法

使用python_2_unicode_compatible装饰器

代码示例:

#! /usr/bin/env python

from future.utils import python_2_unicode_compatible
from sys import version_info

@python_2_unicode_compatible
class SomeClass():
    def __str__(self):
        return "Called __str__"


if __name__ == "__main__":
    some_inst = SomeClass()
    print(some_inst)
    if (version_info > (3,0)):
        print("Python 3 does not support unicode()")
    else:
        print(unicode(some_inst))

django相关资料:

参考资料:http://python.usyiyi.cn/translate/django_182/ref/models/instances.html


相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...