加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-17 17:00:31 所属栏目:Python 来源:网络整理
导读:两则区别: ????__str__()???????????? python2,它返回字节。python3返回的是字符 ????__unicode__()????python3中被弃用 __unicode__ ???? python2? ????用于实现内建的unicode()调用;应该返回一个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


(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读