This article mainly introduces how to create a Python module and import a module. it analyzes the definition, import, and usage skills of the module attributes, and illustrates the concept and usage of the package, for more information about how to create a Python module and how to import a module, see this article. The example analyzes the module definition, how to import and how to use Module attributes, it also describes the concept and usage of the package. For more information, see
This document describes how to create and import Python modules. Share it with you for your reference. The specific analysis is as follows:
The python learning manual says:
Definition module. you only need to use a text editor to input some python code into the text and save it with the. py suffix. any such file will be considered as a python module.
For example, the following code is input into a file and can be viewed as a module:
def printme(var): print varif __name__ == '__main__': printme(1)
If the input is in a. py, import a can import this module.
Then execute a. printme (3) and the screen will print 3:
>>> a.printme(3)3>>>
A variable defined at the top layer of a module automatically becomes a module attribute. For example:
data=[1,2,3]def printme(var): print varif __name__ == '__main__': printme(1)
A data variable is a module attribute. In fact, printme is also a property, just a function.
Example of introducing a module: (assume that data = [1, 2, 3] is not defined at this time)
>>> import a>>> a.dataTraceback (most recent call last): File "
", line 1, in
a.dataAttributeError: 'module' object has no attribute 'data'>>> reload(a)
>>> a.dataTraceback (most recent call last): File "
", line 1, in
a.dataAttributeError: 'module' object has no attribute 'data'>>>
From the above prompt, we can see that the data property is not defined. in this case, we define data = [, 3] in the. py file, reload module a, and output the data property:
>>> reload(a)
>>> a.data[1, 2, 3]>>>
The reload function can reload a module. If the module code is changed, you need to reload it.
The above a. data is the attribute in the access module.
The example above is to import a file as a module.
In fact, the python module imports more content.
In addition to the module name, python can also import the specified directory path. The Directory of python code is called a package. Therefore, this type of import is called package import. In fact, package import turns the directory on the computer into a namespace of python. The attribute is the subdirectory or module file contained in the directory.
Take the following example:
There is an aa folder on my desktop, which contains the bb folder and the. py file in the bb folder.
Put one _ init _. py in the aa and bb folders respectively. then, import aa. bb. a in the command line to import Module.