转换为字符串会引发错误吗? [英] Can a conversion to string raise an error?

查看:70
本文介绍了转换为字符串会引发错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否转换为字符串,即 str(sth)是否会引发异常,例如 float(sth)是吗?
我想问一下是否需要将我的代码包装在:

I was wondering if converting to string i.e. str(sth) can raise an exception like for example float(sth) does? I am asking this to know if it is necessary to wrap my code in:

try:
    x = str(value)
except ValueError:
    x = None

这在Python 2和3中也有所不同,因为 str 类与它们不同?

Also does this differ in Python 2 and 3, since the str class is different in them??

推荐答案

如果遇到自定义类,该类显式在 __ str __ (如果未定义 __ str __ ,则为 __ repr __ )。或者,例如,一个类从 __ str __ 返回 bytes 个对象:

If you encounter a custom class that explicitly raises an exception in __str__ (or __repr__ if __str__ is not defined). Or, for example a class that returns a bytes object from __str__:

class Foo:
    def __str__(self):
        return b''

str(Foo()) # TypeError: __str__ returned non-string (type bytes)

但就我个人而言,我没有 看到了这一点,我很确定没有人知道。这样做很愚蠢。同样,在 __ str __ 的实现中发生愚蠢的错误或极端情况可能会导致另一个 Exception 。有趣的是,您知道如何将Python推入这些极端情况(请参阅 @ user2357112

But personally, I have never seen this and I'm pretty sure no one has; it would be daft to do it. Likewise, a silly mistake in the implementation of __str__ or edge cases might create another Exception. It is interesting to see how you could push Python to these edge cases (look at @user2357112 answer here).

在这种情况下,没有内置函数通常会引发异常,因为它是在中为所有它们定义的Py2 Py3

Other than that case, no built-ins generally raise an exception in this case since it is defined for all of them in Py2 and Py3.

对于用户定义的类 str 将使用 object .__ str __ 默认情况下,如果未在Python 3中定义,则在Python 2中,如果类是新样式类(继承自 object ),请使用它。

For user defined classes str will use object.__str__ by default if not defined in Python 3 and, in Python 2, use it if a class is a new style class (inherits from object).

如果一个类是我相信的旧类,则是 classobj .__ str __ 用于类和 instance .__ str __ (实例)。

If a class is an old style class I believe it is classobj.__str__ that is used for classes and instance.__str__ for instances.

总的来说,我不会理解这一点,特殊情况还不够特殊。

In general, I would not catch this, special cases aren't special enough for this.

这篇关于转换为字符串会引发错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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