Python的字符串和unicode强制魔术函数如何工作?

Python的字符串和unicode强制魔术函数如何工作?,第1张

概述我使用的是Python版本:2.7.3.在Python中,我们使用魔术方法__str__和__unicode__来定义我们的自定义类上的str和unicode的行为:>>> class A(object): def __str__(self): print 'Casting A to str' return u'Stri

我使用的是Python版本:2.7.3.

在Python中,我们使用魔术方法__str__和__unicode__来定义我们的自定义类上的str和unicode的行为:

>>> class A(object):  def __str__(self):    print 'Casting A to str'    return u'String'  def __unicode__(self):    print 'Casting A to unicode'    return 'Unicode'>>> a = A()>>> str(a)Casting A to str'String'>>> unicode(a)Casting A to unicodeu'Unicode'

该行为表明__str__和__unicode__的返回值被强制转换为str或unicode,具体取决于运行哪种魔术方法.

但是,如果我们这样做:

>>> class B(object):  def __str__(self):    print 'Casting B to str'    return A()  def __unicode__(self):    print 'Casting B to unicode'    return A()>>> b = B()>>> str(b)Casting B to strTraceback (most recent call last):  file "

调用str.mro()和unicode.mro()表示两者都是basestring的子类.但是,__ unicode__还允许返回缓冲区对象,缓冲区对象直接从对象继承而不从basetring继承.

所以,我的问题是,调用str和unicode时实际发生了什么? __str__和__unicode__对str和unicode使用的返回值要求是什么?

最佳答案

However,__unicode__ also allows returning of buffer objects,which
directly object and don’t inherit from basestring.

这是不正确的. unicode()可以转换字符串或缓冲区.这是使用默认编码将传递的参数转换为unicode的“最佳尝试”(这就是为什么它表示强制).它将始终返回一个unicode对象.

So,my question is,what actually happens when str and unicode are
called? What are the return value requirements on __str__ and
__unicode__ for use in str and unicode?

__str__应返回对象的非正式,人性化的字符串表示.当有人在您的对象上使用str(),或者您的对象是print语句的一部分时,就会调用此方法.

__unicode__应该总是返回一个unicode对象.如果未定义此方法,则调用__str__,然后将结果强制转换为unicode(通过将它们传递给unicode()).

在第二个示例中,您将返回无效对象,这就是您看到错误消息的原因.您的第一个示例似乎适用于__unicode__,因为副作用,但它也没有正确编写.

有关这些“魔术方法”的更多信息和详细信息,请阅读文档的data model部分. 总结

以上是内存溢出为你收集整理的Python的字符串和unicode强制/魔术函数如何工作?全部内容,希望文章能够帮你解决Python的字符串和unicode强制/魔术函数如何工作?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1205339.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)