为了账号安全,请及时绑定邮箱和手机立即绑定

在python中删除返回的变量

在python中删除返回的变量

红糖糍粑 2023-02-07 17:30:13
我正在为 python 编写代码,我想知道是否可以按照以下方式做一些事情:def Theoretical_Function(Variable):    print(Variable)    newvarcontainer = Variable    return newvarcontainer    #del newvarcontainer也就是删除返回的变量,但仍然从函数中返回它
查看完整描述

1 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

每个定义的函数都有自己的命名空间。当您退出函数(使用返回语句)时,命名空间将被垃圾收集,并且不会执行该函数的其他语句。


def func(a):

  print(a)

  b = a

  #the return statement exits the function

  return b

  #the following statements will NOT be executed

  a, b = 1,2

  a, b = b+1, 5

#We call the function

y = func(1)

#Now y is 1

#You cen del y and it will become inaccessible

del y

#This will throw an error:

print(y)

Python 在内部使用引用。当声明


y = 1

被执行时,Python 解释器为值 1 保留内存。然后它将引用分配给 1 的内存位置。当您分配另一个变量时


c = 1

它会将相同的引用分配给 c。您可以使用 id 函数验证这一点。


>>> id(c)

1234567

>>> id(y)

1234567

id(c) 和 id(y) 将返回相同的值,这意味着它们指向内存中的相同位置。如您所见,python 解释器将只在内存中存储一次不可变值。


查看完整回答
反对 回复 2023-02-07
  • 1 回答
  • 0 关注
  • 97 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信