folks,

乡亲,

The result of the following code is [] Why is it not ['0','1','2']? If I want to make psswd equal to number in the function foo, what should I do?

以下代码的结果是[]为什么不是['0','1','2']?如果我想让psswd等于函数foo中的数字,我该怎么办?

number = ['0','1','2']
def foo(psswd):
    psswd = number[:]

if __name__ == '__main__':
    psswd = []
    foo(psswd)
    print psswd

3 个解决方案

#1


1

Your code:

你的代码:

number = ['0','1','2']
def foo(psswd):
    psswd = number[:]

if __name__ == '__main__':
    psswd = []
    foo(psswd)
    print psswd

psswd = number[:] rebinds local variable psswd with a new list.

psswd = number [:]用新列表重新绑定局部变量psswd。

I.e., when you do foo(psswd), function foo is called, and local variable passwd inside it is created which points to the global list under the same name.

即,当你执行foo(psswd)时,会调用函数foo,并在其中创建局部变量passwd,该变量指向同名的全局列表。

When you do psswd = <something> inside foo function, this <something> is created/got and local name psswd is made to point to it. Global variable psswd still points to the old value.

当你在foo函数中执行psswd = 时,会创建/获取此 ,并使本地名称psswd指向它。全局变量psswd仍指向旧值。

If you want to change the object itself, not the local name, you must use this object's methods. psswd[:] = <smething> actually calls psswd.__setitem__ method, thus the object which is referenced by local name psswd is modified.

如果要更改对象本身而不是本地名称,则必须使用此对象的方法。 psswd [:] = 实际上调用了psswd .__ setitem__方法,因此修改了本地名称psswd引用的对象。

更多相关文章

  1. 用python写MapReduce函数——以WordCount为例
  2. Python基础(4) - 变量
  3. python闭包变量迟邦定
  4. Python内置函数介绍
  5. 判断变量是否是DataFrame 或者 Series
  6. Python学习之路:函数的非固定参数
  7. 函数参数中裸星号的目的是什么?
  8. 创建单独的函数而不是一个大的缓慢处理时间?
  9. Python:lambda表达式实现求两个变量的最大值

随机推荐

  1. Android官方入门文档[6]添加Action按钮
  2. Android 编写使用root权限的android应用
  3. android 随手记 遍历文件夹下的文件有多
  4. 开发板部分总结
  5. android SQLite 事物处理
  6. 57.EasyRecyclerViewSidebar
  7. Android Studio生成APK自动追加版本号
  8. Android support 26升级到28特性总结
  9. 基于Android不同版本对应notification机
  10. Android 通话记录分析