之前在 PyCharm 中定义的 Python 重新声明变量 [英] Python redeclared variable defined before in PyCharm
问题描述
在编写了这段单独执行数据库查询的代码后,PyCharm 用给定的注释突出显示了第二个 i.
for i in range(records):fill.apply_proc('AddCompany', gen_add_company())对于 i 在范围内(记录):fill.apply_proc('AddConference', gen_add_conference())
<块引用>
重新声明上面定义的i",但不使用.
它会不会有任何错误?我应该以其他方式实现它吗?
发生的情况是与您在 C++/Java 中遇到的范围不同.在那里,您希望 i
不存在于 for
之间.事实并非如此.
你可以在工作中看到,假设记录 == 10:
for i in range(records):fill.apply_proc('AddCompany', gen_add_company())打印(我:%d"%我)对于 i 在范围内(记录):fill.apply_proc('AddConference', gen_add_conference())
你会得到你的输出 - 假设 for
没有输出:
i: 9
您收到警告的原因可能是这种事情可能会导致大脑崩溃的错误.间接解决方案包含在链接页面中;您可以考虑将您的 for
封装在一个函数中,如果这种情况发生两次以上,这可能特别有助于提高可读性.
在 列表推导式,但不是在您要问的 Python 3 中.
After having written this piece of code to execute queries on database separately, PyCharm highlighted the second i with the given comment.
for i in range(records):
filler.apply_proc('AddCompany', gen_add_company())
for i in range(records):
filler.apply_proc('AddConference', gen_add_conference())
Redeclared 'i' defined above without usage.
Could it be subject of any error? Should I achieve it in other way?
What happens is the different scoping than you would get in, say, C++/Java. There you'd expect i
not to exist between for
s. It's not the case.
You could see that in work, assuming records == 10:
for i in range(records):
filler.apply_proc('AddCompany', gen_add_company())
print("i: %d" % i)
for i in range(records):
filler.apply_proc('AddConference', gen_add_conference())
You'd get in your output - assuming no output from for
:
i: 9
The reason why you're getting the warning is probably that this kind of thing could lead to brain-cracking bugs. Indirect solutions are included in the linked page; one you could consider is to encase your for
in a function, which might be especially good for readability if this happens more than twice.
There's also a similar case of scoping surprise in list comprehensions, but not in Python 3 you're asking about.
这篇关于之前在 PyCharm 中定义的 Python 重新声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!