一、基本模块

shutil

文件、目录、压缩包的处理模块

shutil.copyfile(src, dst)
拷贝文件 >>> shutil.copyfile('a.log','b.log')
‘b.log'
-rw-r--r-- 1 jack wheel 4 2 25 15:59 a.log
-rw-r--r-- 1 jack wheel 4 2 25 16:03 b.log
shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变 >>> shutil.copymode('a.log','b.log’)
jackdeMacBook-Pro:python jack$ ll total 16 -rw-r--r-- 1 jack wheel 4 2 25 15:59 a.log -rwxr-xr-x 1 jack wheel 4 2 25 16:03 b.log* jackdeMacBook-Pro:python jack$ ll total 16 -rw-r--r-- 1 jack wheel 4 2 25 15:59 a.log -rw-r--r-- 1 jack wheel 4 2 25 16:03 b.log
shutil.copystat(src, dst)
拷贝状态的信息,包括:mode bits, atime, mtime, flags >>> shutil.copystat('a.log','b.log')
jackdeMacBook-Pro:python jack$ stat a.log
16777220 6143218 -rw-r--r-- 1 jack wheel 0 4 "Feb 25 16:03:07 2016" "Feb 25 15:59:52 2016" "Feb 25 15:59:52 2016" "Feb 25 15:59:52 2016" 4096 8 0 a.log
jackdeMacBook-Pro:python jack$ stat b.log
16777220 6143570 -rw-r--r-- 1 jack wheel 0 4 "Feb 25 16:03:07 2016" "Feb 25 16:03:07 2016" "Feb 25 16:06:11 2016" "Feb 25 16:03:07 2016" 4096 8 0 b.log
jackdeMacBook-Pro:python jack$ stat b.log
16777220 6143570 -rw-r--r-- 1 jack wheel 0 4 "Feb 25 16:03:07 2016" "Feb 25 15:59:52 2016" "Feb 25 16:07:28 2016" "Feb 25 15:59:52 2016" 4096 8 0 b.log
shutil.copy(src, dst)
拷贝文件和权限 >>> shutil.copy('a.log','b.log')
‘b.log'
jackdeMacBook-Pro:python jack$ ll
total 16
-rw-r--r-- 1 jack wheel 4 2 25 15:59 a.log
-rwxr-xr-x 1 jack wheel 11 2 25 16:09 b.log*
jackdeMacBook-Pro:python jack$ ll
total 16
-rw-r--r-- 1 jack wheel 4 2 25 15:59 a.log
-rw-r--r-- 1 jack wheel 4 2 25 16:09 b.log
shutil.copy2(src, dst)
拷贝文件和状态信息 >>> shutil.copy2('a.log','c.log’)
‘c.log'
-rw-r--r-- 1 jack wheel 4 2 25 15:59 a.log
-rw-r--r-- 1 jack wheel 4 2 25 16:09 b.log
-rw-r--r-- 1 jack wheel 4 2 25 15:59 c.log
jackdeMacBook-Pro:python jack$ stat a.log
16777220 6143218 -rw-r--r-- 1 jack wheel 0 4 "Feb 25 16:11:26 2016" "Feb 25 15:59:52 2016" "Feb 25 15:59:52 2016" "Feb 25 15:59:52 2016" 4096 8 0 a.log
jackdeMacBook-Pro:python jack$ stat c.log
16777220 6144432 -rw-r--r-- 1 jack wheel 0 4 "Feb 25 16:11:26 2016" "Feb 25 15:59:52 2016" "Feb 25 16:11:26 2016" "Feb 25 15:59:52 2016" 4096 8 0 c.log
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件
>>> shutil.copytree('a','b')
‘b'
jackdeMacBook-Pro:python jack$ tree
└── a
└── a.log jackdeMacBook-Pro:python jack$ tree
├── a
│ └── a.log
└── b
└── a.log
shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件 >>> shutil.rmtree('b’)
drwxr-xr-x 3 jack wheel 102 2 25 16:13 a/
shutil.move(src, dst)
递归的去移动文件 >>> shutil.move('a','c’)
‘c'
drwxr-xr-x 3 jack wheel 102 2 25 16:13 c/
import shutil #指定压缩后的文件名/压缩方法/源路径
ret = shutil.make_archive('test','zip',root_dir='/Users/jack/Documents/git/github/Demo/days06/test')
#指定压缩后的目标路径和文件名/压缩方法/源路径
ret = shutil.make_archive('/Users/jack/Documents/git/github/Demo/days06/ss','zip',root_dir='/Users/jack/Documents/git/github/Demo/days06/test') #区别 压缩后放置当前程序目录 #解压
import zipfile
z = zipfile.ZipFile('test.zip','r')
z.extractall()
z.close()

xml处理模块

import xml.etree.ElementTree as et

tree = et.parse('t1.xml')
root = tree.getroot()
#print(root.tag) #遍历整个文档
'''
for child in root:
print(child.tag,child.attrib)
for i in child:
print(i.tag,i.text)
'''
#遍历rank节点
'''
for node in root.iter('rank'):
print(node.tag,node.text)
''' '''
#修改节点
for node in root.iter('rank'):
print(node.tag,node.text)
new_rank = int(node.text) + 10
node.text = str(new_rank)
node.set('update','sss')
tree.write('t2.xml')
'''
#删除节点
'''
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 60 :
root.remove(country)
tree.write('t3.xml')
'''
'''
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {
'ServerAliveInterval':'45',
'Compression':'yes',
'ComressionLevel':'9'
}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topSecret.server.com'] = {}
topSecret = config['topSecret.server.com']
topSecret['Host Port'] = '3306'
topSecret['ForwardX11'] = 'no'
config['DEFAULT']['ForwardXll'] = 'yes'
with open('ss1.cfg','w') as configfile:
config.write(configfile)

configparser

用于对特定的配置进行操作

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('ss1.cfg')
['ss1.cfg']
>>> config.sections()
['bitbucket.org', 'topSecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bitbucket.orgs' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topSecret.server.com']
>>> topsecret['host port']
'' >>> for key in config['bitbucket.org']:print(key)
...
user
compression
serveraliveinterval
comressionlevel
forwardxll
>>> config['bitbucket.org']['forwardxll']
'yes' hashlib
import hashlib h = hashlib.md5()
h.update(b'haha')
h.update(b'enenen') msg = h.digest()
msg1 = h.hexdigest()
print(msg)
>>> print(msg)
b'b\xfc\xb2\xd9\x07\x83\x81\x18I\x1a\x0c\xaf\xa6\xdb\xbf\xd7'
>>> print(msg1)
62fcb2d907838118491a0cafa6dbbfd7

subprocess

>>> import subprocess as sub
>>> sub.run('df')
Filesystem 512-blocks Used Available Capacity iused ifree %iused Mounted on
/dev/disk1 234586112 138600696 95473416 60% 17389085 11934177 59% /
devfs 371 371 0 100% 642 0 100% /dev
map -hosts 0 0 0 100% 0 0 100% /net
map auto_home 0 0 0 100% 0 0 100% /home
/dev/disk2s1 253425664 37116928 216308736 15% 144988 844956 15% /Volumes/Backup
CompletedProcess(args='df', returncode=0)
>>>sub.run(['df -h'],shell=True)
Filesystem Size Used Avail Capacity iused ifree %iused Mounted on
/dev/disk1 112Gi 66Gi 46Gi 60% 17389072 11934190 59% /
devfs 186Ki 186Ki 0Bi 100% 642 0 100% /dev
map -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net
map auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /home
/dev/disk2s1 121Gi 18Gi 103Gi 15% 144988 844956 15% /Volumes/Backup
CompletedProcess(args=['df -h'], returncode=0)
>>> sub.run(['df -h'],shell=True,stdout=subprocess.PIPE)
CompletedProcess(args=['df -h'], returncode=0, stdout=b'Filesystem Size Used Avail Capacity iused ifree %iused Mounted on\n/dev/disk1 112Gi 66Gi 46Gi 60% 17389258 11934004 59% /\ndevfs 186Ki 186Ki 0Bi 100% 642 0 100% /dev\nmap -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net\nmap auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /home\n/dev/disk2s1 121Gi 18Gi 103Gi 15% 144988 844956 15% /Volumes/Backup\n')

logging

用于便捷记录日志且线程安全的模块

日志可以分为 debug(), info(), warning(), error() and critical() 5个级别

import logging

logging.debug('this is a debug messages!')
logging.info('this is a info messages!')
logging.warning('this is a warning messages!')
logging.critical('this is a critical messages!!!') logging.basicConfig(format='%(asctime)s %(message)s',datefmt='%Y-%m-%d %H:%M',filename='access.log',level=logging.INFO)
logging.debug('This messages should go to the access.log!')
logging.info('This is info!')
logging.warning('This is warning') logger = logging.getLogger('Test')
logger.setLevel(logging.DEBUG) ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG) fh = logging.FileHandler('access.log')
fh.setLevel(logging.WARNING)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter)
fh.setFormatter(formatter) logger.addHandler(ch)
logger.addHandler(fh) logger.debug('debug')
logger.info('info..')
logger.warn('warn!')
logger.error('error!!')
logger.critical('critical!!!')

二、初识面向对象

什么是类?
动物、人、山等都是类。
什么是对象?
对象即类的实体,小明就是对象。
什么是方法?
定义一个类的功能,小明会吃饭就是方法。
什么是继承?
继承父类,小明也有黑色的头发.
什么是封装?
小明不能像袋鼠一样蹦。
什么是多态性?
拍一巴掌,可能是很大的力气,也可能是很温柔的。
什么是抽象性?
简化复杂的现实的问题途径,可以给任何问题找到恰当的类的定义,比如空气。

类就是一个模板,模板里包括很多函数,函数可以实现很多功能。对象就是根据模板创建的实例,通过实例化对象可以执行类里面的函数。

如何定义一个类?
类是对现实世界中一些事物的封装,可以用下面的方式来定义:
class Role(object):
    block

在block里面就可以定义属性和方法。定义完类后,就产生一个类对象。类对象支持引用和实例化。引用是通过类对象去调用类中的属性或者方法。而实例化是产生出一个类对象的实例,称作实力对象。
    由于类可以起到模板的作用,因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。通过定义一个特殊的__init__方法,在创建实例的时候,就把life_value等属性绑上去:

class Role(object):
def __init__(self,name,armor,weapon,life_value=100,money=0):
self.name = name
self.armor = armor
self.weapon = weapon
self.life_value = life_value
self.money = money

和普通的函数相比,在类中定义的函数只有一点不同,就是第一个参数永远是实例变量self,并且,调用时,不用传递该参数。除此之外,类的方法和普通函数没有什么区别,所以,你仍然可以用默认参数、可变参数、关键字参数和命名关键字参数。

class Role(object):
def __init__(self,name,armor,weapon,life_value=100,money=0):
self.name = name
self.armor = armor
self.weapon = weapon
self.life_value = life_value
self.money = money
def damage(self):
pass

Python 模块续和面向对象的介绍(六)的更多相关文章

  1. Python开发基础-Day17面向对象编程介绍、类和对象

    面向对象变成介绍 面向过程编程 核心是过程(流水线式思维),过程即解决问题的步骤,面向过程的设计就好比精心设计好一条流水线,考虑周全什么时候处理什么东西.主要应用在一旦完成很少修改的地方,如linux ...

  2. Python 模块续 configparser、shutil、XML、paramiko、系统命令、

    一.configparse # 注释1 ; 注释2 [section1] # 节点 k1 = v1 # 值 k2:v2 # 值 [section2] # 节点 k1 = v1 # 值 1.获取所有节点 ...

  3. python模块之datetime方法详细介绍

    datetime Python提供了许多内置模块用于操作时间日期,如calendar,time,datetime,这篇文章主要是对datetime进行汇总,datetime模块的借口实现原则更加直观, ...

  4. python模块之calendar方法详细介绍

    calendar,是与日历相关的模块.calendar模块文件里定义了很多类型,主要有Calendar,TextCalendar以及HTMLCalendar类型.其中,Calendar是TextCal ...

  5. python(23)- 面向对象简单介绍

    面向概述 面向过程:根据业务逻辑从上到下写垒代码 面向过程的设计的核心是过程,过程即解决问题的步骤, 面向过程的设计就好比精心设计好一条流水线,考虑周全什么时候处理什么东西 优点:极大降低了程序的复杂 ...

  6. python模块之time方法详细介绍

    >>> import time >>> dir(time) ['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__nam ...

  7. python 模块加载

    python 模块加载 本文主要介绍python模块加载的过程. module的组成 所有的module都是由对象和对象之间的关系组成. type和object python中所有的东西都是对象,分为 ...

  8. 详解Python模块导入方法

    python常被昵称为胶水语言,它能很轻松的把用其他语言制作的各种模块(尤其是C/C++)轻松联结在一起.python包含子目录中的模块方法比较简单,关键是能够在sys.path里面找到通向模块文件的 ...

  9. Python模块的介绍

    Python模块的学习: 1.os模块: 下面只对os模块中几个比较常用的方法做一些简单的示例: os.system():这个方法在shell中体现的比较多,在dos命令行中也可以执行,下面就以在do ...

随机推荐

  1. Android 开发笔记 “Sqlite数据库删除”

    1.代码方式 Context.deleteDatabase(String databaseName);//删除某一数据库 2.设置里面 进入应用程序 ,然后清除数据就ok了

  2. codeforces 620F. Xors on Segments

    题目链接 定义一种操作f(u, v) = u^u+1^.......^v. (u<=v), 给n个数, q个询问, 每个询问给出一个区间[l, r], 求这个区间里的f(a[i], a[j]) ...

  3. ORA-20000:ORU-10027:buffer overflow,limit of 10000 bytes错误4

    今天再测试一个存储过程时,用DBMS_OUTPUT.PUT_LINE输出时,报 ORA-20000:ORU-10027:buffer overflow,limit of 10000 bytes SQL ...

  4. Wmic-linux

    Description Windows Management Instrumentation Command-line (WMIC) uses Windows Management Instrumen ...

  5. C/C++中的内存管理

    一.内存的分配方式 1. 程序代码区 2. 静态数据区 3. 动态数据区 二.动态内存 1. 在栈上创建的内存 2. 从堆上分配的内存 3. 小结 三.指针与内存 1. 操作内存 2. 指针与数组 3 ...

  6. Android PNG渐变背景图片失真问题 getWindow().setFormat(PixelFormat.RGBA_8888);

    最近一个困扰很久的问题,渐变效果的png图片,设置为控件图片或background时,在eclipse上看着没有什么问题,但是在设备上运行时,可以看到明显的一圈圈的轮廓线,图片严重失真.在网上goog ...

  7. js获取中英文长度

    function getLength(str) {    var len = str.length;    var reLen = 0;    for (var i = 0; i < len; ...

  8. JS浏览器类型推断方法

    在网站的前端开发,浏览器兼容性问题这已经让我们抢,Chrome但也生出不知道多少麻烦,我们增加. 浏览器兼容性将由前端开发框架解决的第一个问题.要解决的兼容性问题必须首先准确推断浏览器的类型和它的版本 ...

  9. Ext JS学习第三天 我们所熟悉的javascript(二)

    •javascript之函数 •对于Ext开发者,我还是希望你能对javascript原生的东西非常了解.甚至熟练掌握运用.那么函数,无疑是非常重要的概念.首先在前面一讲,我们知道了函数也是一种数据类 ...

  10. MVC DI

    using System;using Microsoft.Practices.Unity; public class BizInstanceFactory { private static reado ...