Basic usage of Python packages and classes, and Python package usage

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.