http://blog.csdn.net/liukang325/article/details/46724365
Create a folder Filepackage
Create __init__.py within the Filepackage folder
With __init__.py, Filepackage is a package, otherwise it is just a normal folder.
Create file.py within the Filepackage folder
The file.py code is as follows:
#!/usr/bin/env Python3#-*-Coding:utf-8-*-From datetimeImport datetimeClassMyFile():Def__init__(Self, filepath): print (' MyFile init ... ') Self.filepath = FilePathdef printfilepath (self): print ( Self.filepath) def testReadFile< Span class= "Hljs-params" (self): with open (Self.filepath, ' R ' ) as f:s = F.read () print ( ' open for read ... ') print (s) def testwritefile (self): with Open ( ' test.txt ', ' W ') as f:f.write ( ' today is ') F.write (DateTime.Now (). Strftime ( '%y-%m-%d ')
The __init__.py code is as follows:
from file import MyFile
The common class method inside this module is leaking out
Then the outside reference does not have to find the actual location, to find the __init__ of the package is good
Establish main.py and filepackage-lateral,
The main.py code is as follows:
#!/usr/bin/env python3# -*- coding: utf-8 -*-from filePackage import MyFileif __name__ == ‘__main__‘: a = MyFile("./filePackage/test.txt") a.printFilePath(); a.testReadFile();
Directory structure:
If __init__.py not write anything, then in the main.py can also write:
import filePackage.fileif __name__ == ‘__main__‘: a = filePackage.file.MyFile("./filePackage/test.txt") a.printFilePath();
However, it is not recommended to do so, and it is recommended to expose the common classes in the module as described above and refer directly to them.
Basic usage of Python packages and classes