Python basic tutorial package and class usage, python basic tutorial
Python basic tutorial package and class 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 in this way. We recommend that you expose the public classes in the module as described above and reference them directly.
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!