【问题标题】:Is everything in Python castable to a string?Python中的所有内容都可以转换为字符串吗?
【发布时间】:2020-06-18 23:01:37
【问题描述】:

我正在尝试在 Python 中找到一个无法转换为字符串的示例。

>>> str(None)
'None'
>>> str(False)
'False'
>>> str(5)
'5'
>>> str(object)
"<class 'object'>"
>>> class Test:
...     pass
...
>>> str(Test)
"<class '__main__.Test'>"
>>> str(Test())
'<__main__.Test object at 0x7f7e88a13630>'

整个 Python 世界中是否有任何东西不能转换为 str

【问题讨论】:

  • 阅读__str__魔术方法。
  • Evey python ovject 继承自 object,它定义了一个 __str__,所以出于实际目的,是的。请注意,“演员”是一个定义松散的术语。但它在像 C 这样的低级静态类型语言中意味着一个特定的东西。IMO 在 Python 中使用它不是一个好术语。

标签: python string casting type-conversion theory


【解决方案1】:

Python 中的所有内容都可以转换为字符串吗?

不!

>>> class MyObject():
...     def __str__(self):
...         raise NotImplementedError("You can't string me!")
...
>>> str(MyObject())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __str__
NotImplementedError: You can't string me!

【讨论】:

  • 酷!哪些类不会在 __str__ 方法中引发 NotImplementedError?似乎除了创建引发错误的__str__ 方法之外,所有内容都可以转换为字符串。
  • @sneilan 因为一切都继承自 objectobject 定义了一个行为良好的(如果大部分没用的话)__str__没有没有坏的对象-表现得没有定义自己的不良行为。我不知道当您尝试对它们进行字符串化时会引发错误的任何 stdlib 类型(但它们可能存在!)
【解决方案2】:

来自__str__ 文档:

The default implementation defined by the built-in type object
calls object.__repr__().

object.__repr__ 打印对象名称和地址(至少在 cpython 中)。这就是您的输出'&lt;__main__.Test object at 0x7f7e88a13630&gt;' 的来源。一个类必须覆盖__str__ 并引发异常(或有错误)才能失败。这样做没有什么理由,而且你很难找到一个不是为特定目的而设计的。

【讨论】:

  • 所以一切都可以转换为 str 除非你重写 __str__ 方法。
  • 是的,即便如此,如果不实现返回字符串的__str__,你也得发疯了。你可以编写一个带有__init__ 的类来擦除硬盘驱动器。那也不是很好。
  • @sneilan 或者除非你根本没有定义__str__,而是重写__repr__ 方法而不是返回一个字符串。
猜你喜欢
  • 1970-01-01
  • 2023-04-01
  • 2010-09-10
  • 1970-01-01
  • 2014-09-03
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2023-03-11
相关资源
最近更新 更多