且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么 *args 参数解包会给出一个元组?

更新时间:2023-02-14 17:00:19

我不知道这是否是它背后的想法,但是处理起来很容易(即使实例化一个 listtuple 数据并不难)可能会出现令人困惑的行为.

I don't know if this was the thinking behind it, but that ease of processing (even though instantiate a list with the tuple data is not that hard) would come at possible confusing behavior.

def fce1(*args):
   fce2(args)
   # some more code using args

def fce2(args):
   args.insert(0, 'other_val')

fce1(1, 2, 3)

编写 fce1 代码的人可能会感到惊讶,因为他们没有意识到他们稍后处理的 args 不是调用函数的内容.

Could surprise people writing fce1 code not realizing that args they deal with later on are not what the function was called with.

我还认为不可变类型在内部更容易处理并且开销更少.

I would also presume immutable types are easier to deal with internally and come with less overhead.