正在拆分的 Python 用户定义的异常字符串

标签 python string exception init

新的 python 用户 (2.7.5)。

尝试实现一个简单的异常。异常派生类采用字符串输入参数并将它们拆分为单个字符。

我在教程和 stackoverflow 上浏览了大约 90 分钟,但没有找到答案。

# Meaningless base class.
class base:
    def __init__(self):
        self.base = 1

# Somewhat useful test of string storage.
class test(base):
    def __init__(self, arg):
        self.args = arg

这会产生:

>>> a = test('test')
>>> a.args
'test'

但是当我尝试时:

# No qualitative difference between this and the above definition,
# except for 'Exception'.
class test(Exception):
    def __init__(self, arg):
        self.args = arg

我得到:

>>> a = test('test')
>>> a.args
('t', 'e', 's', 't')

唯一的变化是类继承。

我希望在我的异常类中将我的字符串合并为一个片段,这样我就可以实际打印和阅读它们。发生了什么事?

最佳答案

Exception 类使 args 成为属性(数据描述符)with this setter :

static int
BaseException_set_args(PyBaseExceptionObject *self, PyObject *val)
{
    PyObject *seq;
    if (val == NULL) {
        PyErr_SetString(PyExc_TypeError, "args may not be deleted");
        return -1;
    }
    seq = PySequence_Tuple(val);
    if (!seq) return -1;
    Py_CLEAR(self->args);
    self->args = seq;
    return 0;
}

线

seq = PySequence_Tuple(val);

将值转换为元组。

所以在你的 Python 代码中,

    self.args = arg

触发 setter 并导致 self.args 被设置为一个元组。

关于正在拆分的 Python 用户定义的异常字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17048143/

相关文章:

python - 如何在 Python 对象上搜索/查找方法或属性? (搜索所有后代)

string - GoLang的字符串映射键有字符串长度限制吗?

string - Lua中将字符串分割成二维表

c# - 为什么超出范围的索引不会为 Regex GroupCollection 抛出异常?

C#函数无法返回——阻止编译器警告

python - 无法在 VS Code 中导入

python - 添加 ssml 字符串后,我的 Azure 文本转语音应用程序不再输出

python - 为什么 Tkinter 在打包滚动条时会卡住?

java - 在数组中搜索特定字符串

java - JUnit 在预期异常后继续断言