Why static binding works differently for class and function?

做~自己de王妃 提交于 2019-12-04 04:24:29

Yes - it seems that the documentation is rather misleading. A class definition doesn't actually work quite the same as other normal blocks:

global_one = 0

class A(object):
    x = global_one + 10
    global_one = 100
    y = global_one + 20
    del global_one
    z = global_one + 30

a = A()
print a.x, a.y, a.z, global_one

results in: 10, 120, 30, 0

if you try the same thing with a function, you get an UnboundLocalError on your first access of global_one.

The reason for this is that class definitions as normal have access to the parent scope, however, all name assignments do NOT modify a local scope, but in fact are captured into the class's data attributes dictionary. There are hints about this in the documentation, but it's certainly not obvious.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!