当前位置:网站首页>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函数为什么这么特殊
边栏推荐
- JESD204B时钟网络
- 肿瘤免疫治疗研究丨ProSci LAG3抗体解决方案
- String (explanation)
- Anr principle and Practice
- How can flinksql calculate the difference between a field before and after update when docking with CDC?
- This article introduces you to the characteristics, purposes and basic function examples of static routing
- Learning records on July 4, 2022
- 分布式id解决方案
- Kotlin之 Databinding 异常
- 【mysqld】Can't create/write to file
猜你喜欢
带你刷(牛客网)C语言百题(第一天)
[noi simulation] regional division (conclusion, structure)
Pinduoduo lost the lawsuit: "bargain for free" infringed the right to know but did not constitute fraud, and was sentenced to pay 400 yuan
企業如何進行數據治理?分享數據治理4個方面的經驗總結
JWT的基础介绍
Maze games based on JS
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
FPGA课程:JESD204B的应用场景(干货分享)
数据资产管理与数据安全国内外最新趋势
ESXI挂载移动(机械)硬盘详细教程
随机推荐
企业如何进行数据治理?分享数据治理4个方面的经验总结
Navicat importing 15g data reports an error [2013 - lost connection to MySQL server during query] [1153: got a packet bigger]
Bus message bus
大促过后,销量与流量兼具,是否真的高枕无忧?
剑指offer-高质量的代码
SolidWorks GB Library (steel profile library, including aluminum profile, aluminum tube and other structures) installation and use tutorial (generating aluminum profile as an example)
工具类:对象转map 驼峰转下划线 下划线转驼峰
Postgresql源码(59)分析事务ID分配、溢出判断方法
ANR 原理及实践
服装门店如何盈利?
mobx 知识点集合案例(快速入门)
「运维有小邓」符合GDPR的合规要求
Problems and precautions about using data pumps (expdp, impdp) to export and import large capacity tables in Oracle migration
[noi simulation] regional division (conclusion, structure)
学术报告系列(六) - Autonomous Driving on the journey to full autonomy
Kotlin之 Databinding 异常
ViewModelProvider.of 过时方法解决
jdbc数据库连接池使用问题
Matlab tips (30) nonlinear fitting lsqcurefit
What books can greatly improve programming ideas and abilities?