当前位置:网站首页>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函数为什么这么特殊
边栏推荐
- 学术报告系列(六) - Autonomous Driving on the journey to full autonomy
- 算法---比特位计数(Kotlin)
- 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
- Kotlin之 Databinding 异常
- Linear algebra (1)
- Get the city according to IP
- How can gyms improve their competitiveness?
- 基于JS的迷宫小游戏
- LM11丨重构K线构建择时交易策略
- Can't you really do it when you are 35 years old?
猜你喜欢

网络基础 —— 报头、封装和解包

Big coffee gathering | nextarch foundation cloud development meetup is coming

What books can greatly improve programming ideas and abilities?

二十岁的我4面拿到字节跳动offer,至今不敢相信

JWT certification

Please answer the questions about database data transfer

品牌·咨询标准化

从零到一,教你搭建「CLIP 以文搜图」搜索服务(二):5 分钟实现原型

How can clothing stores make profits?

LC 面试题 02.07. 链表相交 & LC142. 环形链表II
随机推荐
Matlab tips (29) polynomial fitting plotfit
JDBC database connection pool usage problem
Config distributed configuration center
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
Please ask a question, flick Oracle CDC, read a table without update operation, and repeatedly read the full amount of data every ten seconds
品牌电商如何逆势增长?在这里预见未来!
Stack and queue-p79-9
Under what circumstances should we consider sub database and sub table
DHCP路由器工作原理
Anr principle and Practice
请教一下,监听pgsql ,怎样可以监听多个schema和table
多个kubernetes集群如何实现共享同一个存储
Unity C# 函数笔记
联合索引ABC的几种索引利用情况
LM11丨重构K线构建择时交易策略
Prime partner of Huawei machine test questions
SolidWorks的GB库(钢型材库,包括铝型材、铝管等结构)安装及使用教程(生成铝型材为例)
一文带你了解静态路由的特点、目的及配置基本功能示例
impdp的transform参数的测试
Navicat importing 15g data reports an error [2013 - lost connection to MySQL server during query] [1153: got a packet bigger]