简体   繁体   English

Python中的隐式参数传递?

[英]Implicit Argument Passing in Python?

The code below is from hackermeter.com and I'm not sure what to think of it. 下面的代码来自hackermeter.com,我不知道该怎么想。 Is the variable i being passed implicitly to run() or does it expect more modification than just where it specifies? 变量i是隐式传递给run()还是期望更多修改而不是它指定的位置?

import sys

def run():
   # Code here!

for i in range(int(sys.stdin.readline())):
   run()

I'd argue that this is a poor coding practice. 我认为这是一个糟糕的编码实践。 The only reason run() has access to i is that i is global. run()访问i的唯一原因是i是全球性的。

The following is arguably better as it will force the programmer to pass i into run() explicitly (if required): 以下可以说是更好,因为它会强制程序员明确地将i传递给run() (如果需要):

import sys

def run():
   # Code here!

def main():
   for i in range(int(sys.stdin.readline())):
      run()

if __name__ == '__main__':
   main()

This is the code in the question: 这是问题中的代码:

import sys

def run():
   # Code here!

for i in range(int(sys.stdin.readline())):
   run()

i is defined in global scope (that is at the top level of the module), and so is accessible inside run . i在全局范围内定义(即在模块的顶层),因此可以在run访问。 This is because essentially only functions and classes introduce a new local scope, so an iteration variable is a normal variable of its enclosing scope. 这是因为基本上只有函数和类引入了一个新的局部作用域,因此迭代变量是其封闭作用域的正常变量。

If run does access i , this creates the potential for an error if i has not already been defined (eg if a conditional statement prevented the loop from being executed at all). 如果run不接i ,这对于一个错误造成如果潜在的i尚未确定(例如,如果一个条件语句防止从所有正在执行的循环)。

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

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