两则区别:
__str__() python2,它返回字节。python3返回的是字符
__unicode__() python3中被弃用
__unicode__
python2
用于实现内建的unicode()调用;应该返回一个Unicode对象。当该方法没有定义时,则尝试使用字符串转换,并且将字符串转换的结果,使用系统默认的编码转换为Unicode。
在python2由于兼容性问题,应该将所有的字符串格式化__unicode__(),并创建一个存根__str__()方法:
def __str__(self): return unicode(self).encode('utf-8')
在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)
使用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