博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python 函数参数传递机制.
阅读量:7027 次
发布时间:2019-06-28

本文共 2187 字,大约阅读时间需要 7 分钟。

learning python,5e中讲到.Python的函数参数传递机制是对象引用.

Arguments are passed by assignment (object reference). In Python, arguments

are passed to functions by assignment (which, as we’ve learned, means by object
reference). As you’ll see, in Python’s model the caller and function share objects
by references, but there is no name aliasing. Changing an argument name within
a function does not also change the corresponding name in the caller, but changing
passed-in mutable objects in place can change objects shared by the caller, and
serve as a function result.

 

SO上有一个很好的说明:

The problem comes from a misunderstanding of what variables are in Python. If you're used to most traditional languages, you have a mental model of what happens in the following sequence:

a =1a =2

You believe that a is a memory location that stores the value 1, then is updated to store the value 2. That's not how things work in Python. Rather, a starts as a reference to an object with the value 1, then gets reassigned as a reference to an object with the value 2. Those two objects may continue to coexist even though a doesn't refer to the first one anymore; in fact they may be shared by any number of other references within the program.

When you call a function with a parameter, a new reference is created that refers to the object passed in. This is separate from the reference that was used in the function call, so there's no way to update that reference and make it refer to a new object. In your example:

self.variable = 'Original'    self.Change(self.variable)def Change(self, var):    var = 'Changed'
 

self.variable is a reference to the string object 'Original'. When you call Change you create a second reference var to the object. Inside the function you reassign the reference var to a different string object 'Changed', but the reference self.variable is separate and does not change.

The only way around this is to pass a mutable object. Because both references refer to the same object, any changes to the object are reflected in both places.

self.variable = ['Original']    self.Change(self.variable)def Change(self, var):    var[0] = 'Changed'

 

转载于:https://www.cnblogs.com/xiangnan/p/3403539.html

你可能感兴趣的文章
NumberFormat注解 DateTimeFormat
查看>>
[转载]PV操作简单理解
查看>>
Acm Dima and Lisa的题解
查看>>
2017 ZSTU寒假排位赛 #7
查看>>
MSSQL_打开xp_cmdshell
查看>>
(转)win7英文目录和中文目录,文件夹的别名
查看>>
MySQL进阶
查看>>
mybatis分页 -----PageHelper插件
查看>>
从移动硬盘启动电脑与重装注意事项
查看>>
深入浅出Tomcat系列
查看>>
从网页提取的关键字
查看>>
杭州手持式超声波流量计的特点汇总
查看>>
位运算符
查看>>
【OCP-12c】CUUG 071题库考试原题及答案解析(18)
查看>>
Centos7系统如何不重启系统识别新添加的硬盘?
查看>>
【Unity Shader】自定义材质面板的小技巧
查看>>
icon文件操作
查看>>
BeatSaber节奏光剑双手柄MR教程
查看>>
分组聚合
查看>>
冒泡排序(bubble sort)
查看>>