Python中__main__方法中的变量使用

前言

__main__方法作为Python编程环境的程序入口,可以定义一些变量,这些变量默认为全局变量,可供其他方法使用。但是使用的过程需要注意一些事项,否则会出现报错。

在这里插入图片描述

__main__方法中的变量

import argparse

# TracelessLe注:代码示例,不可直接执行

def test_fun1():
    print("pathA: ", pathA)

if __name__ == "__main__":
	parser = argparse.ArgumentParser(
        'Options for test.')
    parser.add_argument("--pathA", type=str, required=True,
                        help="the path of results")  # 指定路径
    args = parser.parse_args()
    pathA = args.pathA
	
	test_fun1()  # 调用test_fun1()方法

在上述代码中,pathA 在__main__方法中定义,默认为全局(global)变量,可以供test_fun1()方法调用,能够正常打印。

尝试修改__main__方法中的变量

import argparse
import os

# TracelessLe注:代码示例,不可直接执行

def test_fun2():
    if pathA.endswith('/'):
    	pathA = pathA[:-1]  #  此处尝试修改pathA,会报错
    pathA = os.path.basename(pathA)
    print("pathA: ", pathA)

if __name__ == "__main__":
	parser = argparse.ArgumentParser(
        'Options for test.')
    parser.add_argument("--pathA", type=str, required=True,
                        help="the path of results")  # 指定路径
    args = parser.parse_args()
    pathA = args.pathA
	
	test_fun2()  # 调用test_fun2()方法

在上述代码中,pathA 在__main__方法中定义,默认为全局(global)变量(如果其它方法调用pathA时不加global声明的话pathA可视为常量),但是在test_fun2()方法中,尝试对pathA变量进行修改后赋值,此时pathA会被解释器解释为test_fun2方法的局部变量。因此在运行过程中会遇到下面的报错:

Traceback (most recent call last):
File "test.py", line 12, in
test_fun2()
File "test.py", line 12, in test_fun2
if pathA.endswith('/'):
UnboundLocalError: local variable 'pathA' referenced before assignment

正确使用__main__方法中的变量

import argparse
import os

# TracelessLe注:代码示例,不可直接执行

def test_fun3():
   	if pathA.endswith('/'):
        pathA_name = os.path.basename(pathA[:-1])  # 使用切片,不会改变pathA变量本身
    else:
        pathA_name = os.path.basename(pathA)
    print("pathA_name: ", pathA_name )

if __name__ == "__main__":
	parser = argparse.ArgumentParser(
        'Options for test.')
    parser.add_argument("--pathA", type=str, required=True,
                        help="the path of results")  # 指定路径
    args = parser.parse_args()
    pathA = args.pathA
	
	test_fun3()  # 调用test_fun3()方法

在上述代码中,pathA 在__main__方法中定义,默认为全局(global)变量,在test_fun3()方法中,尝试使用新的局部变量存储pathA的切片,此时作为全局变量的pathA不变,因此程序可以正常运行。或者在test_fun2方法中第一次调用pathA之前声明“global pathA”后再使用,如下所示:


>>> if __name__ == "__main__":
...     pathA = "aaa"
... 
>>> def test():
...     print(pathA)
...     pathA = "xxx"
...     print(pathA)
... 
>>> test()
Traceback (most recent call last):   
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in test
UnboundLocalError: local variable 'pathA' referenced before assignment

>>> def test2():
...     print(pathA)
...     global pathA
...     pathA = "xxx"
...     print(pathA)
... 
  File "<stdin>", line 3
SyntaxError: name 'pathA' is used prior to global declaration

>>> def test3():
...     global pathA
...     print(pathA)
...     pathA = "xxx"
...     print(pathA)
... 
>>> test3()
aaa
xxx
>>> pathA
'xxx'

引申

除了在__main__中定义全局变量外,还可以在文件开头使用global显式声明全局变量。不过通常不这么做。一般仅会在文件头使用全大写变量名定义全局常量。

版权说明

本文为原创文章,独家发布在blog.csdn.net/TracelessLe。未经个人允许不得转载。如需帮助请email至tracelessle@163.com
在这里插入图片描述

参考资料

[1] python中定义全局变量的方法 - 编程语言 - 亿速云
[2] main — Top-level code environment — Python 3.10.3 documentation

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TracelessLe

❀点个赞加个关注再走吧❀

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值