Python 模块续和面向对象的介绍(六)

一、基本模块

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
上一篇:VS2015如何新建MVC空模版项目


下一篇:<图形图像,动画,多媒体> 读书笔记 --- 力学行为特性