Python包和类的基本用法
来源:互联网 发布:淘宝返现规定 编辑:程序博客网 时间:2024/06/05 10:37
转自: http://blog.csdn.net/liukang325/article/details/46724365
参考:http://www.runoob.com/python/python-modules.html
Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句。
包是一个分层次的文件目录结构,它定义了一个由模块及子包,和子包下的子包等组成的 Python 的应用环境。简单来说,包就是文件夹,但该文件夹下必须存在__init__.py 文件, 该文件的内容可以为空。__init__.py用于标识当前文件夹是一个包。
演示:
建立一个文件夹filePackage
在filePackage 文件夹内创建__init__.py
有了__init__.py,filePackage才算是一个包,否则只是算一个普通文件夹。
在filePackage 文件夹内创建 file.py
file.py 代码如下:
#!/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('今天是 ') f.write(datetime.now().strftime('%Y-%m-%d'))
__init__.py 代码如下:
原文章中少了
#!/usr/bin/env python3#from file import MyFile #原文章中少了filePackage,会提示找不到file模块from filePackage.file import MyFile# -*- coding: UTF-8 -*-if __name__ == '__main__': print('作为主程序运行')else: print('filePackage包初始化')
把本模块里面的公用的类 方法 暴漏出来,然后 外面的引用 不用找到具体的现实位置,找到包的init 就好了.
建立main.py 和 filePackage 平级,
main.py 代码如下:
#!/usr/bin/env python3# -*- coding: utf-8 -*-#无需指定MyFile类在filePackage包中的具体位置,因为已经在__init__文件中指定.from filePackage import MyFileif __name__ == '__main__': a = MyFile("./test.txt") a.printFilePath(); a.testReadFile();
阅读全文
1 0
- Python包和类的基本用法
- Python包和类的基本用法
- python中类的基本用法
- python中包管理工具(easy_install和pip的用法)
- python中包的用法
- python中 *args和**kwargs的基本用法
- [python]Graphlab的基本用法
- 用Python做测试——Requests包的基本用法
- Python signal模块包介绍和用法
- python range和list基本用法
- 模块和包的用法
- 【python】redis基本命令和基本用法详解
- Python 数据处理扩展包: pandas 模块的DataFrame介绍(创建和基本操作)
- map的基本用法和嵌套用法
- python 之 lambda 表达式的基本用法
- Python正则式的基本用法
- python str.format()方法的基本用法
- Python 自动化测试 的 基本用法实例
- Mathematic for Computer Science Lecture 1
- 算法谜题36 有限的差异
- Exchange发送邮件
- SSH连接VMware中NAT模式主机
- leetcode 1. Two Sum排序+双指针
- Python包和类的基本用法
- 2017.05.19回顾 TSS = ESS + RSS证明
- oracle 聚合函数 LISTAGG ,将多行结果合并成一行
- 【javascript】关于localstorage的使用感想
- Web应用中使用JavaMail发送邮件
- 常用SQL Server 小语法、函数 等的实例汇总
- 20个实用的webApp前端开发技巧
- UML类图关系(泛化 、实现、依赖、关联、聚合、组合)
- 一起来写一个简易的手风琴效果