当前位置:网站首页>main函数在import语句中的特殊行为
main函数在import语句中的特殊行为
2022-07-07 03:11:00 【胜天半子_王二_王半仙】
先说结论, import module时会执行module函数级别代码, 但是如果该module中有main函数, 并不会执行.
听起来比较复杂, 看下下面的代码就懂了, 也有一部分问题没有解决, 希望大佬来教学下
test_02.py
from test_03 import test_print
x = None
print 'test_02 execute'
def get_x():
global x
print 'get_X'
return x
def set_x():
global x
print 'set_x'
x = 10
if __name__ == '__main__':
print 'execute main'
set_x()
print get_x()
print '===================================='
test_print()
test_03.py
def test_print():
import test_02 as x
print x.x
上面test_02执行, 调用了test_03中的 test_print(), test_print去打印test_02中的全局变量x, 却发现还是默认值,这是为什么呢?
看下打印结果
原来是test_03中执行import语句的时候, 执行了test_02中函数级别的语句, 并且如果我们给代码再改一改, 加上id, 看一下:test_02
if __name__ == '__main__':
print 'execute main'
set_x()
print get_x()
print '===================================='
test_print()
print get_x()
print id(x)
test_03
def test_print():
from test_02 import x
print x
print id(x)
执行结果
我们发现id都不一样
也就是说test_03中import x的时候不仅执行了一遍test_02中的代码, 甚至都不是同一个对象了
但是如果我们把set_x()从main函数中提出到外面, 再看一遍结果
id又一样了, 这是为什么呢? 有没有大佬来解释一下main函数为什么这么特殊
边栏推荐
猜你喜欢

Config分布式配置中心

Data of all class a scenic spots in China in 2022 (13604)

7天零基础能考证HCIA吗?华为认证系统学习路线分享

Pinduoduo lost the lawsuit: "bargain for free" infringed the right to know but did not constitute fraud, and was sentenced to pay 400 yuan

SolidWorks的GB库(钢型材库,包括铝型材、铝管等结构)安装及使用教程(生成铝型材为例)

Answer to the first stage of the assignment of "information security management and evaluation" of the higher vocational group of the 2018 Jiangsu Vocational College skills competition

Brand · consultation standardization

MOS tube parameters μ A method of Cox

使用TCP/IP四层模型进行网络传输的基本流程
![Navicat importing 15g data reports an error [2013 - lost connection to MySQL server during query] [1153: got a packet bigger]](/img/13/096857158c9f977f8677f7cd0f9d4b.png)
Navicat importing 15g data reports an error [2013 - lost connection to MySQL server during query] [1153: got a packet bigger]
随机推荐
「运维有小邓」符合GDPR的合规要求
Installing redis and windows extension method under win system
LVS+Keepalived(DR模式)学习笔记
偏执的非合格公司
Mysql---- import and export & View & Index & execution plan
Redhat5 installing vmware tools under virtual machine
剑指offer-高质量的代码
7天零基础能考证HCIA吗?华为认证系统学习路线分享
Tool class: object to map hump to underline underline hump
ESXI挂载移动(机械)硬盘详细教程
ANR 原理及实践
Under what circumstances should we consider sub database and sub table
【luogu P1971】兔兔与蛋蛋游戏(二分图博弈)
How can clothing stores make profits?
Config分布式配置中心
Libcurl returns curlcode description
Navicat importing 15g data reports an error [2013 - lost connection to MySQL server during query] [1153: got a packet bigger]
Several index utilization of joint index ABC
2018年江苏省职业院校技能大赛高职组“信息安全管理与评估”赛项任务书第一阶段答案
DHCP路由器工作原理