Python文档似乎不清楚参数是通过引用还是值传递,以下代码生成未更改的值'Original'
class PassByReference:
def __init__(self):
self.variable = 'Original'
self.change(self.variable)
print(self.variable)
def change(self, var):
var = 'Changed'
Run Code Online (Sandbox Code Playgroud)
有什么我可以通过实际参考传递变量吗?
我正在尝试理解Python的变量范围方法.在这个例子中,为什么f()能够改变x内部感知main()的价值,而不是价值n?
def f(n, x):
n = 2
x.append(4)
print('In f():', n, x)
def main():
n = 1
x = [0,1,2,3]
print('Before:', n, x)
f(n, x)
print('After: ', n, x)
main()
Run Code Online (Sandbox Code Playgroud)
输出:
Before: 1 [0, 1, 2, 3]
In f(): 2 [0, 1, 2, 3, 4]
After: 1 [0, 1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud) 当你将一个像list,array这样的集合传递给python中的另一个函数时,是否会复制它,或者它只是一个指针?
我希望下面的代码只会初始化dict_a,dict_b以及dict_c字典.但它接触到副本通过效果:
dict_a = dict_b = dict_c = {}
dict_c['hello'] = 'goodbye'
print dict_a
print dict_b
print dict_c
Run Code Online (Sandbox Code Playgroud)
如您所见,结果如下:
{'hello': 'goodbye'}
{'hello': 'goodbye'}
{'hello': 'goodbye'}
Run Code Online (Sandbox Code Playgroud)
为什么该程序会给出以前的结果,当我希望它返回时:
{}
{}
{'hello': 'goodbye'}
Run Code Online (Sandbox Code Playgroud) 我正在通过Udacity和Dave Evans介绍了关于列表属性的练习
list1 = [1,2,3,4]
list2 = [1,2,3,4]
list1=list1+[6]
print(list1)
list2.append(6)
print(list2)
list1 = [1,2,3,4]
list2 = [1,2,3,4]
def proc(mylist):
mylist = mylist + [6]
def proc2(mylist):
mylist.append(6)
# Can you explain the results given by the four print statements below? Remove
# the hashes # and run the code to check.
print (list1)
proc(list1)
print (list1)
print (list2)
proc2(list2)
print (list2)
Run Code Online (Sandbox Code Playgroud)
输出是
[1, 2, 3, 4, 6]
[1, 2, 3, 4, 6]
[1, 2, 3, 4]
[1, 2, 3, …Run Code Online (Sandbox Code Playgroud)