How to write your own package, your own library, and call your own library in python

When writing a huge project, it is inevitable to carry out some encapsulation. Generally, function encapsulation and class encapsulation can be carried out, but if there are many encapsulation modules, it will be more convenient to encapsulate the utility library.

  • First create a folder, the name can be chosen by yourself, we use it to encapsulate a library, and then we can put some package module py files written by ourselves into this folder, the directory structure is as follows

aaeeae90c5eb48f391d9d653dc65c8e2.png

  • But in order for the python system to realize that this is a package, it is necessary to create such a py file in the folder——__init__.py file, and each import package name is equivalent to calling the __init__.py file, which is quite to execute it.

59cc6dcbba5d42e9bb9ccb36eff697ed.png

Let's talk about another error-prone import form

For example, my_module is a folder package we created, text1 is a packaged py file module, hello is a function in the text1.py file. If we want to import the method in the module in the following way, an error will occur

import my_module
my_module.test1.hello()
#AttributeError: module 'my_module' has no attribute 'test1'

Solution: Import all the modules in the package in the __init__.py file

from temp import  text1

from temp import  text2

 

In this way, it will be no problem to call it like before.

import my_module
my_module.test1.hello()

 success~

Guess you like

Origin blog.csdn.net/weixin_63676550/article/details/129771882