突变参数的Python函数的正确样式 [英] Correct Style for Python functions that mutate the argument

查看:129
本文介绍了突变参数的Python函数的正确样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个Python函数,该函数可以改变其中一个参数(它是一个列表,即可变的).像这样:

I would like to write a Python function that mutates one of the arguments (which is a list, ie, mutable). Something like this:

def change(array):
   array.append(4)

change(array)

我更喜欢按值传递而不是Python的设置(无论您决定调用它).所以我通常会写这样的函数:

I'm more familiar with passing by value than Python's setup (whatever you decide to call it). So I would usually write such a function like this:

def change(array):
  array.append(4)
  return array

array = change(array)

这是我的困惑.由于我只能更改参数,因此第二种方法似乎是多余的.但是第一个感觉不对.此外,我的特定函数将具有多个参数,只有其中一个会更改.第二种方法可以清楚地知道正在更改的参数(因为已将其分配给变量).第一种方法没有给出指示.有约定吗?哪个更好'?谢谢.

Here's my confusion. Since I can just mutate the argument, the second method would seem redundant. But the first one feels wrong. Also, my particular function will have several parameters, only one of which will change. The second method makes it clear what argument is changing (because it is assigned to the variable). The first method gives no indication. Is there a convention? Which is 'better'? Thank you.

推荐答案

第一种方式:

def change(array):
   array.append(4)

change(array)

是最惯用的方式.通常,在python中,我们希望函数可以改变参数或返回 1 .这样做的原因是因为如果一个函数什么都不返回,那么就很清楚地表明该函数必须具有某些副作用才能证明它的存在(例如,对输入进行突变).

is the most idiomatic way to do it. Generally, in python, we expect a function to either mutate the arguments, or return something1. The reason for this is because if a function doesn't return anything, then it makes it abundantly clear that the function must have had some side-effect in order to justify it's existence (e.g. mutating the inputs).

另一方面,如果您以第二种方式做事:

On the flip side, if you do things the second way:

def change(array):
  array.append(4)
  return array

array = change(array)

您很容易难以发现错误的突变,而当您不希望它发生变化时,可变对象突然发生了变化-但是我认为change进行了复制" ...

you're vulnerable to have hard to track down bugs where a mutable object changes all of a sudden when you didn't expect it to -- "But I thought change made a copy"...

1 技术上每个函数都会返回某物,即_something_恰好是None ...

1Technically every function returns something, that _something_ just happens to be None ...

这篇关于突变参数的Python函数的正确样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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