编程技术网

关注微信公众号,定时推送前沿、专业、深度的编程技术资料。

 找回密码
 立即注册

QQ登录

只需一步,快速开始

极客时间

Python异常-如何自动设置args属性?:Python exception - how does the args attribute get automatically set?

soglad Python 2022-5-11 10:55 5人围观

腾讯云服务器
Python异常-如何自动设置args属性?的处理方法

假设我定义了以下异常:

Suppose I define the following exception:

>>> class MyError(Exception): ... def __init__(self, arg1): ... pass 

然后我实例化该类以创建一个异常对象:

Then I instantiate the class to create an exception object:

>>> e = MyError('abc') >>> e.args ('abc',) 

这是如何设置 args 属性的?(在 __ init __ 中,我什么也没做.)

Here how is the args attribute getting set? (In the __init__, I am doing nothing.)

问题解答

args 通过 __ get __ __ set __ 方法实现为数据描述符.

args is implemented as a data descriptor with __get__ and __set__ methods.

这发生在 BaseException .__ new __ 内部,就像提到的@bakatrouble一样.除其他外, BaseException .__ new __ 内部发生的事情大致类似于以下Python代码:

This takes place inside BaseException.__new__ like @bakatrouble mentioned. Among other things, what happens inside BaseException.__new__ is roughly like the Python code below:

class BaseException: def __new__(cls, *args): # self = create object of type cls self.args = args # This calls: BaseException.args.__set__(self, args) ... return self 

Python 3.7.0 alpha 1 的C代码中,上面的Python代码看起来像这样(检查Python的C代码是否存在过去或将来的差异):

In C code of Python 3.7.0 alpha 1, the above Python code looks like this (inspect Python's C code for any past or future differences):

BaseException_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { # other things omitted... self = (PyBaseExceptionObject *)type->tp_alloc(type, 0); # many things follow... if (args) { self->args = args; Py_INCREF(args); return (PyObject *)self; } # many more things follow } 

交互式实验:

>>> e = Exception('aaa') >>> e Exception('aaa',) 

>>> BaseException.args.__set__(e, ('bbb',)) >>> e Exception('bbb',) >>> BaseException.args.__get__(e) ('bbb',) 

因此,当 BaseException 的对象或 BaseException 的对象出现在 BaseException .__ new __ 中时, args 的神奇灵感就使您的眼睛望向天堂.将创建其任何子类.

Hence, the magical inspiration of args that makes your eyes look heavenward takes place in BaseException.__new__, when an object of BaseException or any of its sub-classes is created.

这篇关于Python异常-如何自动设置args属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!

腾讯云服务器 阿里云服务器
关注微信
^