我试图了解python中@main注释的用法。使用以下python程序,
def cube(x):
return x * x * x
def run_tests():
printf("Should be 1:", cube(1))
printf("Should be 8:", cube(2))
printf("Should be 27:", cube(3))
@main
def main():
print("Starting")
run_tests()
print("Ending.")
我收到以下错误:
PS C:\Users\MOHET01\Desktop> python.exe -i .\cube.py
Traceback (most recent call last):
File ".\cube.py", line 9, in <module>
@main
NameError: name 'main' is not defined
>>>
从ucb导入的函数如下所示:
def main(fn):
"""Call fn with command line arguments. Used as a decorator.
The main decorator marks the function that starts a program. For example,
interact()
@main
def my_run_function():
# function body
Use this instead of the typical __name__ == "__main__" predicate.
"""
if inspect.stack()[1][0].f_locals['__name__'] == '__main__':
args = sys.argv[1:] # Discard the script name from command line
print(args)
print(*args)
print(fn)
fn(*args) # Call the main function
return fn
我的问题:
尽管我使用内部名称main定义函数,但为什么会看到此错误?
该@main
装饰在你的课程提供了一个文件来实现,但是你有没有进口的。您链接的页面说要使用
from ucb import main, interact
ucb.py
在程序中导入功能。
至于错误为什么这样说name 'main' is not defined
,这是因为在装饰器执行之前,函数定义实际上并未完成任何定义。main
装饰器和装饰函数的名称重用令人困惑;将main
在@main
从不同的功能main
你定义def main(): ...
。在main
中@main
定义,如果该文件被运行的脚本运行装饰功能,而main
在def main(): ...
将要运行的功能。
我强烈建议您不必使用这种装饰器。执行装饰器执行的任务的标准方法是编写
if __name__ == '__main__':
whatever_function_you_would_have_put_the_decorator_on()
或者,如果您想像装饰器一样处理命令行参数,
if __name__ == '__main__':
import sys
whatever_function_you_would_have_put_the_decorator_on(*sys.argv[1:])
装饰器是一种试图隐藏问题的尝试sys.argv
,__name__
因此您不必了解它们,但这有问题。如果您尝试编写如下内容:
@main
def hello():
print(hello_string)
hello_string = 'Hi there.'
您会得到一个NameError
,因为hello_string
直到装饰器运行之后才被分配。如果您在本课程之外继续编写Python,则会发现使用if __name__ == '__main__'
此工具比使用装饰器更容易出错,并且对其他程序员更易理解。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句