企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 1. __path__ ` __init__.py`的常用变量__path__, 默认情况下只有一个元素, 就是当前包的路径, 修改__path__, 可以修改此包内的搜索路径. ~~~ if __name__ == '__main__': import pythonpackage # 导入pythonpackage包,其__init.py自动执行 ~~~ ![](https://box.kancloud.cn/4949e0c1096acd37b63d6177910a0218_1176x614.png) 当前此包的搜索路径:['E:\\PythonTest\\pythonpackage'] ### 举例1: 在Utils下增加2个目录Linux和Windows, 并各有一个echo.py文件, 目录如下 ~~~ Sound/Utils/ |-- Linux 目录下没有__init__.py文件, 不是包, 只是一个普通目录 | `-- echo.py |-- Windows 目录下没有__init__.py文件, 不是包, 只是一个普通目录 | `-- echo.py |-- __init__.py |-- echo.py |-- reverse.py `-- surround.py ~~~ 三个echo.py的文件内容如下: ~~~ ltt@hz171-14:~/tmp$cat Sound/Utils/echo.py print"I'm Sound.Utils.echo" ltt@hz171-14:~/tmp$cat Sound/Utils/Windows/echo.py print"I'm Windows.echo" ltt@hz171-14:~/tmp$cat Sound/Utils/Linux/echo.py print"I'm Linux.echo" ~~~ `Sound/Utils/__init__.py`是空文件,则结果如下: ~~~ >>>import Sound.Utils.echo # 此时导入是Utils下的echo模块 I'm Sound.Utils.echo ~~~ 把`Sound/Utils/__init__.py`改成: ~~~ import sys import os print"Sound.Utils.__init__.__path__ before change:",__path__ dirname=__path__[0] if sys.platform[0:5]=='linux': __path__.insert(0,os.path.join(dirname,'Linux')) else: __path__.insert(0,os.path.join(dirname,'Windows')) print"Sound.Utils.__init__.__path__ AFTER change:",__path__ ~~~ 则结果如下: ~~~ # 导入echo模块时,因为Utils包搜索路径变成了:['Sound/Utils/Linux','Sound/Utils'],所以搜索到了Sound/Utils/Linux下的 # echo模块,所以会执行可执行语句print >>>import Sound.Utils.echo Sound.Utils.__init__.__path__beforechange:['Sound/Utils'] Sound.Utils.__init__.__path__AFTERchange:['Sound/Utils/Linux','Sound/Utils'] I'm Linux.echo ~~~ ### 举例2 ![](https://box.kancloud.cn/df3468e791b5562d43721d5c66f0ad34_390x149.png) ~~~ def walk_modules(path): """Loads a module and all its submodules from the given module path and returns them. If *any* module throws an exception while importing, that exception is thrown back. For example: walk_modules('scrapy.utils') """ from pkgutil import iter_modules # 遍历所有python包 mods = [] mod = import_module(path) # 导入包中的__init__.py模块,__init__.py模块中含有__path__变量,指向当前包路径 mods.append(mod) if hasattr(mod, '__path__'): for _, subpath, ispkg in iter_modules(mod.__path__): fullpath = path + '.' + subpath if ispkg: mods += walk_modules(fullpath) # 如果是包(含有__init.py文件),继续遍历 else: submod = import_module(fullpath) # 如果是模块直接导入 mods.append(submod) return mods if __name__ == '__main__': module = walk_modules('pythonpackage') print(module) ~~~ ~~~ ['E:\\PythonTest\\pythonpackage'] # __init__.py模块 print(__path__) ['E:\\PythonTest\\pythonpackage\\test'] # __init__.py模块 print(__path__) [<module 'pythonpackage' from 'E:\\PythonTest\\pythonpackage\\__init__.py'>, <module 'pythonpackage.packagtest' from 'E:\\PythonTest\\pythonpackage\\packagtest.py'>, <module 'pythonpackage.settings' from 'E:\\PythonTest\\pythonpackage\\settings.py'>, <module 'pythonpackage.test' from 'E:\\PythonTest\\pythonpackage\\test\\__init__.py'>, <module 'pythonpackage.test.packagtest1' from 'E:\\PythonTest\\pythonpackage\\test\\packagtest1.py'>] ~~~ 注意: 1. 包的__init.py文件也会被当做模块导入 2. from pkgutil import iter_modules遍历包,返回 ## 2. ` __dict__` ~~~ __dict__是一个字典,键为属性名,值为属性值; dir()是一个函数,返回的是列表 list,dir()用来寻找一个对象的所有属性,包括__dict__中的属性,__dict__是dir()的子集; ~~~ ~~~ __author__ = 'dailin' import logging import sys class LogTest(object): def __init__(self, name=None, **kwargs): if name is not None: self.name = name elif not getattr(self, 'name', None): raise ValueError("%s must have a name" % type(self).__name__) self.__dict__.update(kwargs) @property def logger(self): logger = logging.getLogger(self.name) # 获取一个logger对象 logger.setLevel(logging.INFO) # 设置日志级别 fmt = logging.Formatter("%(asctime)s - %(spider)s - %(message)s") # 输出格式 h_console = logging.StreamHandler(sys.stdout) # 处理器 h_console.setFormatter(fmt) # 向处理器中添加输出格式 logger.addHandler(h_console) # 把处理器添加到logger对象当中 return logging.LoggerAdapter(logger, {'spider': self}) if __name__ == '__main__': log = LogTest("tuna",hell='mimi') print(log.__dict__) print(log.logger.info("hello")) ~~~ 输出: ~~~ {'name': 'tuna', 'hell': 'mimi'} 2018-04-08 16:48:20,161 - <__main__.LogTest object at 0x00000000025873C8> - hello None ~~~