宁波建设工程检测行业协会网站,企业网站属于广告吗,口碑营销策略有哪些,做一个棋牌网站要多少钱包导入时__init__.py中命令的执行顺序和sys.modules变化
ref: https://edu.csdn.net/skill/practice/python-3-6/164
在有父包和子包的情况下#xff0c;父包中的“ __ init__.py”语句会在子包的“ __ init__.py”语句之前执行#xff0c;然后按下列顺序执行导入子包和模块…包导入时__init__.py中命令的执行顺序和sys.modules变化
ref: https://edu.csdn.net/skill/practice/python-3-6/164
在有父包和子包的情况下父包中的“ __ init__.py”语句会在子包的“ __ init__.py”语句之前执行然后按下列顺序执行导入子包和模块执行“ __ init__.py”中其他代码
需要注意的是如果只导入子包Python解释器会将父包的信息添加到sys.modules中这样导入子包的时候能知道父包的存在但是除了父包的__init__.py中的语句并不会执行其他代码只有需要访问父包时才会进行真正的导入。
sys.modules是一个字典记录的是已经导入的模块信息。首次导入一个模块时python会检查这个模块是否存在于sys.modules中如果已经存在会直接返回模块对象否则导入。
实例 文件结构如下图所示father包含one、two和three三个包one包又包含一个one包。每个 __ init__.py中包含的内容只有一条print语句打印诸如 this is father、this is 1、this is 1.1这样的语句。 leetcode.py中的内容如下所示
import sysif __name__ __main__:for i in range(2):import fatherimport father.one.oneimport father.two#print(sys.modules.keys())del sys.modules[father]del sys.modules[father.one.one]del sys.modules[father.two]print(-----------\n) 输出结果
this is father
this is 1
this is 1.1
this is 2
-----------this is father
this is 1.1
this is 2
-----------这是因为father.one在第一次循环时被加入了sys.modules后续并没有被删除所以再次导入时不会执行father.one的__init__.py语句也就不会输出this is 1。
可变形参匿名和带关键字的
Python函数的参数可以有4种
按位置顺序指定的参数如下面的index带默认值的参数如下面的default没有名字的可选参数如*args有名字的可选参数如**kw
实例
# -*- coding: UTF-8 -*-
def dump(index, default0, *args, **kw):print(打印函数参数)print(---)print(index:, index)print(default:, default)for i, arg in enumerate(args):print(farg[{i}]:, arg)# 注意这里要用kw.items()for key,value in kw.items():print(fkeyword_argument {key}:{value})print()if __name____main__:dump(0)dump(0,2)dump(0,2,Hello,World)dump(0,2,Hello,World, installPython, runPython Program)输出
打印函数参数
---
index: 0
default: 0打印函数参数
---
index: 0
default: 2打印函数参数
---
index: 0
default: 2
arg[0]: Hello
arg[1]: World打印函数参数
---
index: 0
default: 2
arg[0]: Hello
arg[1]: World
keyword_argument install:Python
keyword_argument run:Python Program元组tuple
tuple1 (红色)
for element in tuple1:print(element)
输出
红
色这个输出是因为tuple1实际不是元组是str用type()可知。如果要声明为元组应该用 tuple1 (‘红色’,)