Basic usage of Python packages and classes

Source: Internet
Author: User

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

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.