python globals locals_python – globals(),locals()和vars()之间有什么区别?

每个都返回一个字典:

> globals()总是返回模块命名空间的字典

> locals()总是返回当前命名空间的字典

> vars()返回当前命名空间的字典(如果没有参数调用)或参数的字典。

本地和vars可以使用一些更多的解释。如果在函数内调用locals(),它会构造函数名字空间的字典,并返回它 – 任何进一步的名称赋值不会反映在返回的字典中,并且字典的任何赋值都不会反​​映在实际本地命名空间:

def test():

a = 1

b = 2

huh = locals()

c = 3

print(huh)

huh['d'] = 4

print(d)

给我们:

{'a': 1, 'b': 2}

Traceback (most recent call last):

File "test.py", line 30, in

test()

File "test.py", line 26, in test

print(d)

NameError: global name 'd' is not defined

两个注释:

>这种行为是CPython特有的 – 其他Pythons可能允许更新使其回到本地命名空间

>在CPython 2.x中,可以通过在函数中放置一个exec“pass”行来使它工作。

如果在函数外调用locals(),它返回当前命名空间的实际字典。对命名空间的进一步更改将反映在字典中,对字典的更改将反映在命名空间中:

class Test(object):

a = 'one'

b = 'two'

huh = locals()

c = 'three'

huh['d'] = 'four'

print huh

给我们:

{

'a': 'one',

'b': 'two',

'c': 'three',

'd': 'four',

'huh': {...},

'__module__': '__main__',

}

到目前为止,我所说的关于locals()的所有内容对于vars()也是如此。vars()接受一个单独的对象作为它的参数,如果你给它一个对象,它返回__dict__目的。如果该对象不是函数,则返回的__dict__是该对象的命名空间:

class Test(object):

a = 'one'

b = 'two'

def frobber(self):

print self.c

t = Test()

huh = vars(t)

huh['c'] = 'three'

t.frobber()

这给了我们:

three

如果对象是一个函数,你仍然得到它的__dict__,但除非你做有趣和有趣的东西,它可能不是非常有用:

def test():

a = 1

b = 2

print test.c

huh = vars(test) # these two lines are the same as 'test.c = 3'

huh['c'] = 3

test()

这给了我们:

3

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值