Basic usage of Python packages and classes, and Python package usage
Create a folder filePackage
Create _ init _. py in the filePackage folder.
With _ init _. py, filePackage is regarded as a package; otherwise, it is only a normal folder.
Create file. py in the filePackage folder
The file. py code is as follows:
#! /Usr/bin/env python3 #-*-coding: UTF-8-*-from datetime import datetimeclass MyFile (): def _ init _ (self, filepath ): print ('myfile init... ') self. filepath = filepath def printFilePath (self): print (self. filepath) def testReadFile (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 Code of _ init _. py is as follows:
from file import MyFile
Expose the common class methods in this module
Then, the reference outside does not need to find the actual location. Just find the package's _ init _.
Create a level of main. py and filePackage,
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 nothing is written in _ init _. py, you can also write in main. py as follows:
import filePackage.fileif __name__ == '__main__': a = filePackage.file.MyFile("./filePackage/test.txt") a.printFilePath();
However, it is not recommended to write this statement. We recommend that you follow the above method.Expose the public classes in the module.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.