python函数内部变量 局部变量_函数内部局部变量的生存期(内存范围)

When is the dictionary some_dict destroyed/de-allocated? (when the

function returns?)

首先,一旦你离开这个范围,局部变量就会被销毁。

例如,在函数中,当返回时,将丢失对定义为some_dict的变量的所有引用。因为您返回的是a,如果您没有a_var = some_function()这样的东西,其中a引用将被a_var捕获,那么您也将丢失a。When is the dictionary some_dict created in the memory? (first time

the function is called?)

对于每个方法调用,这里都有一些{'random':'values'}。Should I worry about such things when learning/dealing with python?

是的,请检查下面的示例>>> dictionary = {1: 1, 2: 2}

>>> function()

>>> def function():

dictionary = {1: 2, 2:1}

print dictionary

>>> function()

{1: 2, 2: 1}

>>> dictionary

{1: 1, 2: 2}

在这里,您可能假设您正在重新分配字典,但是python正在创建一个本地字典,在您从函数返回后很快就会丢失how to over come the above issue, use global it would tell that you are trying to reference object define outside the function.>>> def function():

global dictionary

dictionary = {1: 2, 2:1}

print dictionary

>>> function()

{1: 2, 2: 1}

>>> dictionary

{1: 2, 2: 1}Where do I learn about such details of a language? I tried looking in

the docs but couldn't find what I was looking for.

可能问题应该是how do I learn such details,简单易用,理解文档并重新阅读。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值