简体   繁体   English

python - del语句早期执行

[英]python - del statement executing early

I'm a self-taught programmer with no formal training, so please forgive me in advance if this is a stupid question. 我是一名自学成才的程序员,没有接受过正规培训,如果这是一个愚蠢的问题,请提前原谅我。

While programming in Python I found something weird: 在Python编程时我发现了一些奇怪的东西:

from someModule import someClass

def someFunction():
    someInstance = someClass()
    print "foo"
    del someClass

someFunction()

This immediately dies with an unbound local variable error: 这会立即死于未绑定的局部变量错误:

UnboundLocalError: local variable 'someClass' referenced before assignment

Commenting out the delete statement fixes the problem: 注释掉删除语句可以解决问题:

...
    #del someClass
...

and it returns: 它返回:

foo

So, 2 questions: 那么,2个问题:

1) the del statement is at the end of the function. 1)del语句位于函数的末尾。 Why is it being called before the bits at the beginning? 为什么在开始之前调用它?

2) Why is it giving me an "unbound local variable" error? 2)为什么它给我一个“未绑定的局部变量”错误? Shouldn't it be an "unbound global variable" error? 它不应该是一个“未绑定的全局变量”错误吗?

The del statement implicitly renders the name someClass local for the whole function, so the line del语句隐式地为整个函数呈现someClass本地名称,因此该行

someInstance = someClass()

tries to look up a local name someClass , which is not defined at that point. 尝试查找本地名称someClass ,此时未定义。 The del statement isn't executed early -- the name isn't defined right from the beginning. del语句不会提前执行 - 名称从一开始就没有定义。

If you really want to do something like this (hint: you don't), you must declare the name global : 如果你真的想做这样的事情(提示:你没有),你必须声明名称global

def someFunction():
    global someClass
    ...
    del someClass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM