12. Packages in Python

When there are many functional modules in an application or project, it is unreasonable to put them in the same folder; at this time, packages in Python can be used to manage more functional modules. Using packages can effectively avoid name conflicts and facilitate package maintenance and management.


1. Package call

A package is actually a folder or directory that must contain a file named "__init__.py", which can be an empty file, just to indicate that the directory is a package.

Call of the module in the package :
call the hdl() function in the index.py module in the handle package

  • import handle.index #调用handle.index.hdl()
  • from handle import index # 调用 index.hdl()
  • from handle.index import hdl #调用hdl()

2, the initialization of the package

The first time any part of the package is imported, the code in the "__init__.py" file is executed, where variable and function names are also imported automatically. Can include initializing working code for the package and setting the "__all__" variable.

Example of package:

#包的名字bao
#文件名:__init__.py
name = 'MyName'
print('包中的name:', name)
#包中的模块
#文件名:MyPyModel.py
class MyTestModel:
    def __init__(self, value=10):
        self.value = value
    def getValue(self):
        return self.value
    def setValue(self, value):
        self.value = value

if __name__ == '__main__':
    myTest = MyTestModel('ModelTest')
    print(myTest.getValue())
#包的使用
import bao.MyPyModel

if __name__ == '__main__':
    test = bao.MyPyModel.MyTestModel(20)
    print(test.getValue())
    print('outSide:', bao.name)

Running result:
name in the package: MyName
20
outSide: MyName

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325643123&siteId=291194637