当前位置:网站首页>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函数为什么这么特殊
边栏推荐
- impdp的transform参数的测试
- Please ask a question, flick Oracle CDC, read a table without update operation, and repeatedly read the full amount of data every ten seconds
- Config distributed configuration center
- 数据资产管理与数据安全国内外最新趋势
- 请问 flinksql对接cdc时 如何实现计算某个字段update前后的差异 ?
- LVS+Keepalived(DR模式)学习笔记
- from . onnxruntime_ pybind11_ State Import * noqa ddddocr operation error
- Postgresql源码(59)分析事务ID分配、溢出判断方法
- 毕业设计游戏商城
- MATLAB小技巧(30)非线性拟合 lsqcurefit
猜你喜欢
ip地址那点事
如何给目标机器人建模并仿真【数学/控制意义】
MOS tube parameters μ A method of Cox
Brand · consultation standardization
POI export to excel: set font, color, row height adaptation, column width adaptation, lock cells, merge cells
Bus消息总线
Comment les entreprises gèrent - elles les données? Partager les leçons tirées des quatre aspects de la gouvernance des données
带你刷(牛客网)C语言百题(第一天)
ESXI挂载移动(机械)硬盘详细教程
Stack and queue-p78-8 [2011 unified examination true question]
随机推荐
Get the city according to IP
Abnova 体外转录 mRNA工作流程和加帽方法介绍
MySQL的主从复制原理
Under what circumstances should we consider sub database and sub table
栈题目:有效括号的嵌套深度
JWT的基础介绍
Basic introduction of JWT
ip地址那点事
Abnova 膜蛋白脂蛋白体技术及类别展示
MATLAB小技巧(30)非线性拟合 lsqcurefit
Postgresql中procedure支持事务语法(实例&分析)
一文带你了解静态路由的特点、目的及配置基本功能示例
Matlab tips (30) nonlinear fitting lsqcurefit
Several index utilization of joint index ABC
SolidWorks的GB库(钢型材库,包括铝型材、铝管等结构)安装及使用教程(生成铝型材为例)
带你刷(牛客网)C语言百题(第一天)
「运维有小邓」符合GDPR的合规要求
How can flinksql calculate the difference between a field before and after update when docking with CDC?
【mysqld】Can't create/write to file
How to install swoole under window