Python:将对象隐式转换为str? [英] Python: Implicit conversion of object to str?

查看:1025
本文介绍了Python:将对象隐式转换为str?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下代码

  A类:
def __init __(self):
self。 b = B()

def __repr __(self):
#return< A with {} inside& ; A with+ repr(self.b)+inside>
return< A with+ self.b +inside> #TypeError:无法将'B'对象转换为str隐式

类B:
def __repr __(self):
return< B&

a = A()
print(a)



我想知道为什么当添加A的 self.b 到一个字符串时,B __ repr __


解决方案

连接不会导致 self.b 作为字符串求值。您需要明确告诉Python将其强制为字符串。



您可以:

  return< A with+ repr(self.b)+inside> 

但是使用 str.format

  return< A with {} inside>。format(self.b)

然而,jonrsharpe指出,首先尝试调用 __ str __ 存在),为了使其特别使用 __ repr __ ,有以下语法: {!r}

  return< A with {!r} inside>。format(self.b)


Given the following code

class A:
  def __init__(self ):
    self.b = B()

  def __repr__(self):
    #return "<A with {} inside>".format( self.b )
    #return "<A with " + repr(self.b) + " inside>"
    return "<A with " + self.b  + " inside>" # TypeError: Can't convert 'B' object to str implicitly

class B:
  def __repr__(self):
    return "<B>"

a = A()
print(a)

I am wondering why B's __repr__ is not called when "adding" A's self.b to a string.

解决方案

Concatenation doesn't cause self.b to be evaluated as a string. You need to explicitly tell Python to coerce it into a string.

You could do:

return "<A with " + repr(self.b)  + " inside>"

But using str.format would be better.

return "<A with {} inside>".format(self.b)

However as jonrsharpe points out that would try to call __str__ first (if it exists), in order to make it specifically use __repr__ there's this syntax: {!r}.

return "<A with {!r} inside>".format(self.b)

这篇关于Python:将对象隐式转换为str?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆