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-*- fromDatetimeImportDatetime class MyFile(): def __init__(self, filepath):Print' MyFile init ... ') Self.filepath = FilePath def printfilepath(self):Print (Self.filepath) def testreadfile(self): withOpen (Self.filepath,' R ') asF:s = F.read () print (' open for read ... ') print (s) def testwritefile(self): withOpen' Test.txt ',' W ') asF:f.write (' Today is ') F.write (DateTime.Now (). Strftime ('%y-%m-%d '))
The __init__.py code is as follows:
fromimport 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 -*-fromimport MyFileif‘__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‘__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.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Basic usage of Python packages and classes