Python basic tutorial package and class usage, python basic tutorial

Source: Internet
Author: User

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!

Related Article

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.