Python混淆功能参考
发布时间:2020-12-16 22:57:39 所属栏目:Python 来源:网络整理
导读:任何人都可以向我解释为什么a和b下面的两个函数表现不同.函数a在本地更改名称,b更改实际对象. 我在哪里可以找到这种行为的正确文档? def a(names): names = ['Fred','George','Bill']def b(names): names.append('Bill')first_names = ['Fred','George']pri
任何人都可以向我解释为什么a和b下面的两个函数表现不同.函数a在本地更改名称,b更改实际对象.
我在哪里可以找到这种行为的正确文档? def a(names): names = ['Fred','George','Bill'] def b(names): names.append('Bill') first_names = ['Fred','George'] print "before calling any function",first_names a(first_names) print "after calling a",first_names b(first_names) print "after calling b",first_names 输出: before calling any function ['Fred','George'] after calling a ['Fred','George'] after calling b ['Fred','Bill'] 解决方法
函数a创建一个新的本地变量名称并为其分配列表[‘Fred’,’George’,’Bill’].所以现在这是与全局first_names不同的变量,正如您已经发现的那样.
您可以阅读有关修改函数here中的列表的信息. 使函数a的行为与函数b相同的一种方法是使函数成为修饰符: def a(names): names += ['Bill'] 或者你可以做一个纯粹的功能: def c(names): new_list = names + ['Bill'] return new_list 并称之为: first_names = c(first_names) print first_names # ['Fred','Bill'] 纯函数意味着它不会改变程序的状态,即它没有任何副作用,例如改变全局变量. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |