在Python 3裡, assign是call by value? 還是call by reference呢?
Python自創了一個名詞,說是call by assignment.
但是從C語言學起的我,還是用call by value or call by reference來說明,會比較清楚。
如果i is integer, then:
case I:
m = [i]
case II:
m[0] = i
Q: 這兩者差在哪呢?
A:
case I:
m = [i], 是call by value, 也就是把m指向[i]位子的value。
case II:
m[0] = i, 是call by reference, 也就是把m[0]位子的值,設成i.
也許有人會覺得,出來的值都一樣,那有啥差別呢?
請看以下code:
#會印出:
byRef
m= [0]
['good']
m= ['good']
['afternoon']
byValue
m= [0]
['fine.']
m= [0]
['thanks']
byValue1
m= 0
1
m= 0
1
byValue2
m= 0
2
m= 0
2
Python自創了一個名詞,說是call by assignment.
但是從C語言學起的我,還是用call by value or call by reference來說明,會比較清楚。
如果i is integer, then:
case I:
m = [i]
case II:
m[0] = i
Q: 這兩者差在哪呢?
A:
case I:
m = [i], 是call by value, 也就是把m指向[i]位子的value。
case II:
m[0] = i, 是call by reference, 也就是把m[0]位子的值,設成i.
也許有人會覺得,出來的值都一樣,那有啥差別呢?
請看以下code:
class Solution: def byValue(self, t, m = [0]): print('m=', m) for i in t: m = [i] return m def byRef(self, t, m = [0]): print('m=', m) for i in t: m[0] = i return m def byValue1(self, t, m = 0): print('m=', m) for i in t: m = 1 return m def byValue2(self, t, m = 0): print('m=', m) for i in t: m = 2 return m def main(): a = Solution() print('byRef') print(a.byRef(['good'])) print(a.byRef(['afternoon'])) print('byValue') print(a.byValue(['fine.'])) print(a.byValue(['thanks'])) print('byValue1') print(a.byValue1(['good'])) print(a.byValue1(['afternoon'])) print('byValue2') print(a.byValue2(['fine.'])) print(a.byValue2(['thanks'])) if __name__ == "__main__": main()
#會印出:
byRef
m= [0]
['good']
m= ['good']
['afternoon']
byValue
m= [0]
['fine.']
m= [0]
['thanks']
byValue1
m= 0
1
m= 0
1
byValue2
m= 0
2
m= 0
2