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调用的概念(在此处解释http://effbot.org/zone/call-by-object.htm).似乎没有足够的例子来澄清这个概念(或者我的google-fu可能很弱!:D)
我写了这个有点人为的Python程序,试图理解这个概念
def foo( itnumber, ittuple, itlist, itdict ):
itnumber +=1
print id(itnumber) , itnumber
print id(ittuple) , ittuple
itlist.append(3.4)
print id(itlist) , itlist
itdict['mary'] = 2.3
print id(itdict), itdict
# Initialize a number, a tuple, a list and a dictionary
tnumber = 1
print id( tnumber ), tnumber
ttuple = (1, 2, 3)
print id( ttuple ) , ttuple
tlist = [1, 2, 3]
print id( tlist ) , tlist
tdict = tel = {'jack': 4098, 'sape': …Run Code Online (Sandbox Code Playgroud) 这里是ListNote类的定义LeetCode:
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
Run Code Online (Sandbox Code Playgroud)
对于代码:
result = ListNode(0)
#result = 0 -> None
result_tail = result
#result_tail = 0 -> None
result_tail.next = ListNode(1)
#result_tail = 0 -> 1 -> None
#result = 0 -> 1 -> None
result_tail = result_tail.next
#result_tail = 1 -> None
#result = 0 -> 1 -> None
result_tail.next = ListNode(2)
#result_tail = 1 -> 2 -> None
#result = 0 -> 1 …Run Code Online (Sandbox Code Playgroud) 我正在学习 Python,更具体地说,我正在探索范围规则。
我尝试了以下“实验”:
def increment(n):
n += 1
print(n)
return n
n = 1
increment(n)
print(n)
Run Code Online (Sandbox Code Playgroud)
这段代码输出: 2 , 1 ,既然变量 n 返回到全局环境,难道不应该输出 2, 2 吗?
您的建议将不胜感激。