if __name__ == '__main__'

# const.py
PI=3.14

def train():
    print("PI:",PI)
train()
# area.py

from const import PI
 
def calc_round_area(radius):
    return PI * (radius ** 2)
 
def calculate():
    print("round area: ", calc_round_area(2))
 
calculate()
# Run area.py file
PI: 3.14
round area: 12.56
# 可以看见,const.py中的train()也被运行了,实际上我们是不希望它被运行,只是想把 const.py中 PI 变量导入到 area.py
# 现在把 const.py 改一下:
PI = 3.14
 
def train():
    print("PI:", PI)
 
if __name__ == "__main__":
    train()
# 运行area.py文件发现没有执行const.py中train()
round area= 12.56
#丛上述实例可以发现,运行const.py文件时if __name__=="__main__": 语句之前与之后代码都被执行,但作为area.py导入文件时就不会执行if __name__=="__main__": 语句之后代码。

#实际上if __name__=="__main__":就相当于是 Python 模拟的程序入口。由于模块之间相互引用,不同模块可能都有这样的定义,而入口程序只能有一个,选中哪个入口程序取决于 __name__ 的值。

# test.py
print("hahaha")
print(__name__)
 
if __name__ == '__main__':
    print("I'm test.py")
# Run test.py
hahaha
__main__
I'm test.py
#可以发现,此时变量__name__的值为"__main__",即打印“I'm test.py”。如果运行其他文件,通过运行的文件调用本文件,则不会打印该语句,因为程序入口不对,该语句不执行。
# receiver.py
print("receiver_haha")
 
def test():
    print("test can be called!")
 
def receiver_print():
    print("I'm receiver.py")
 
if __name__ == '__main__':
    receiver_print()
# caller.py
import receiver
 
print("caller_haha") 
 
def test():
    print("caller_test can be called!")
  
def caller_print():
    print("I'm caller.py")
  
if __name__ == '__main__':
    caller_print()
    test()
# Run caller.py
receiver_haha
caller_haha
I'm caller.py
caller_test can be called!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值