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

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

发布时间:2020-12-16 21:51:09 所属栏目:Python 来源:网络整理
导读:我使用的是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

我使用的是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 unicode
u'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 str

Traceback (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部分.

(编辑:李大同)

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

    推荐文章
      热点阅读