关于参数传参内存变化的猜想
函数参数设置默认值
我们对Markdown编辑器进行了一些功能拓展与语法支持,除了标准的Markdown编辑器功能,我们增加了如下几点新功能,帮助你用它写博客:
- 传入参数_传入对象(带参数名);
- 传入参数_传入对象(不带参数名);
- 不传入参数 ;
- 传入字符串/整数;
传入参数_传入对象(带参数名)
def n(tip_=[]):
print('--------------------------')
print(tip_, id(tip_))
print('赋值前')
get_value = ctypes.cast(id(tip_), ctypes.py_object).value # 读取地址中的变量
print(id(tip_), get_value)
tip_.append("a")
print('赋值后')
print(tip_, id(tip_))
if __name__ == '__main__':
h=[1,2,3,4]
n(h)
n(h)
运行效果(第一次)
[1, 2, 3, 4] 31778656
赋值前
31778656 [1, 2, 3, 4]
赋值后
[1, 2, 3, 4, ‘a’] 31778656
运行效果(第二次)
[1, 2, 3, 4, ‘a’] 31778656
赋值前
31778656 [1, 2, 3, 4, ‘a’]
赋值后
[1, 2, 3, 4, ‘a’, ‘a’] 31778656
内存中的变化(因为传入的是一个变量,tip_=h)
传入参数_值(不带参数名)
def n(tip_=[]):
print('--------------------------')
print(tip_, id(tip_))
print('赋值前')
get_value = ctypes.cast(id(tip_), ctypes.py_object).value # 读取地址中的变量
print(id(tip_), get_value)
tip_.append("a")
print('赋值后')
print(tip_, id(tip_))
if __name__ == '__main__':
n([1,2,3,4])
n([1,2,3,4])
运行效果(第一次)
[1, 2, 3, 4] 31582088
赋值前
31582088 [1, 2, 3, 4]
赋值后
[1, 2, 3, 4, ‘a’] 31582088
运行效果(第二次)
[1, 2, 3, 4] 31582088
赋值前
31582088 [1, 2, 3, 4]
赋值后
[1, 2, 3, 4, ‘a’] 31582088
内存中的变化
不传入参数
def n(tip_=[]):
print('--------------------------')
print(tip_, id(tip_))
print('赋值前')
get_value = ctypes.cast(id(tip_), ctypes.py_object).value # 读取地址中的变量
print(id(tip_), get_value)
tip_.append("a")
print('赋值后')
print(tip_, id(tip_))
if __name__ == '__main__':
n()
n()
运行效果(第一次)
[] 12643344
赋值前
12643344 []
赋值后
[‘a’] 12643344
运行效果(第二次)
[‘a’] 12643344
赋值前
12643344 [‘a’]
赋值后
[‘a’, ‘a’] 12643344
内存中的变化()
传入字符串/整数时
Python中的字符串是不可变类型,就是说改变一个字符串的元素需要新建一个新的字符串。
以上都是自己在写的时候的猜想,包括查了一些资料,如果有错请大家纠正讨论