Python:将对象隐式转换为str?

处理

给出以下代码

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)

我想知道为什么__repr__在将“ A”添加self.b到字符串时不调用B。

超级重男

串联不会导致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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

TypeError:无法将“ int”对象隐式转换为str

TypeError:无法将“ int”对象隐式转换为str

TypeError:无法将“列表”对象隐式转换为str

无法将“字节”对象隐式转换为str

TypeError:无法将“节点”对象隐式转换为str

“无法将'float'对象转换为隐式str“

TypeError:无法将“模块”对象隐式转换为str

无法将'nonetype'对象隐式转换为str-Python3

python gettext错误:无法将'__proxy__'对象隐式转换为str

Boto3和Python3:无法将“字节”对象隐式转换为str

Python3错误:TypeError:无法将“字节”对象隐式转换为str

Python:TypeError:无法将“生成器”对象隐式转换为str

python3无法将字节隐式转换为对象'str'

无法在python 3.4.3中将'int'对象隐式转换为str

“无法将'int'对象隐式转换为str”错误(Python)

Python 错误:写入 json 文件时无法将“列表”对象隐式转换为 str

无法将“ int”对象隐式转换为str。Python错误

TypeError:无法将'int'对象转换为str隐式错误python

无法将'int'对象隐式转换为str:Python 3+

TypeError:无法将'int'对象隐式转换为str(python)

TypeError-无法将“用户”对象隐式转换为str

Tensorflow TypeError:无法将'numpy.int64'对象转换为隐式str

awscli 错误 - 无法将“NoneType”对象隐式转换为 str

TypeError:无法将“ builtin_function_or_method”对象隐式转换为str

TypeError:使用套接字时无法将“ bytes”对象转换为隐式str

Masonite-TypeError:无法将“未定义”对象隐式转换为str

TypeError:无法在Fib中将'int'对象转换为隐式str

TypeError:对于Pascode系统,无法将“ int”对象隐式转换为str

TypeError:无法将“ float”对象隐式转换为str或TypeError:-:“ str”和“ float”的不受支持的操作数类型