python自动化开发 day03

Author:@南非波波

课程大纲:

day2
http://www.cnblogs.com/wupeiqi/articles/5115190.html

day3
http://www.cnblogs.com/wupeiqi/articles/5133343.html

一、set集合

博客链接:http://www.cnblogs.com/songqingbo/p/5128066.html

优点:访问速度快;
     自带一套解决元素重复的解决方案

测试程序

old_dict = {
    "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#2":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
}
new_dict = {
    "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 800 },
    "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#4":{ 'hostname':'c2', 'cpu_count': 2, 'mem_capicity': 80 },
}

获取三个列表:
    1. 需要更新的列表 update_list
    2. 需要删除的列表 del_list
    3. 需要增加的列表 add_list

代码实现:
    #!/usr/local/env python3
    '''
    Author:@南非波波
    Blog:http://www.cnblogs.com/songqingbo/
    E-mail:qingbo.song@gmail.com
    '''

    old_dict = {
        "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
        "#2":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
        "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    }
    new_dict = {
        "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 800 },
        "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
        "#4":{ 'hostname':'c2', 'cpu_count': 2, 'mem_capicity': 80 },
    }

    #设置set
    old_set = set(old_dict.keys())
    new_set = set(new_dict.keys())

    #更新的set
    update_set = new_set.intersection(old_dict)
    delate_set = old_set.difference(update_set)
    add_set = new_set.difference(update_set)

    update_list = []
    del_list = []
    add_list = []
    # print(update_set)
    # print(delate_set)
    # print(add_set)
    for i in update_set:
        update_list.append({i:new_dict[i]})
        print('需要更新的列表:%s' % update_list)

    for i in delate_set:
        del_list.append({i:old_dict[i]})
        print("需要删除的列表:%s" % del_list)

    for i in add_set:
        add_list.append({i:new_dict[i]})
        print("需要增加的列表:%s" % add_list)

二、collection系列

博客链接:http://www.cnblogs.com/songqingbo/p/5137785.html

不常用功能,需要进行模块功能导入:
    import collection

Counter

常用方法测试:

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import collections

obj = collections.Counter('sjndsjkdsdmslaladsldsldms')

print("输出字符出现的次数字典:")
for k,v in obj.items():
    print("{%s:%s}" % (k,v))

print("输出每一个字符:") #遍历获取原始字符元素
for k in obj.elements():
    print(k)

print("输出前四个出现次数最多的字符:")
for k in obj.most_common(4):
    print(k)


输出结果:
    输出字符出现的次数字典:
    {s:7}
    {l:4}
    {m:2}
    {d:6}
    {k:1}
    {n:1}
    {j:2}
    {a:2}
    输出每一个字符:
    s
    s
    s
    s
    s
    s
    s
    l
    l
    l
    l
    m
    m
    d
    d
    d
    d
    d
    d
    k
    n
    j
    j
    a
    a
    输出前四个出现次数最多的字符:
    ('s', 7)
    ('d', 6)
    ('l', 4)
    ('m', 2)

__missing__

功能:对于不存在的元素,返回计数器为0
import collections
c = collections.Counter('adjsdkskdjksjaksklklakl')
c.__missing__(5)
返回结果:0

most_common

功能:获取出现次数的前几个字母排名
import collections
c = collections.Counter('adjsdkskdjksjaksklklakl')
c.most_common(3)
[('k', 7), ('s', 4), ('a', 3)]
c.most_common(8)
[('k', 7), ('s', 4), ('a', 3), ('j', 3), ('l', 3), ('d', 3)]

elements

功能:计数器中的所有元素,并且按照ascii码进行了排序
    返回一个迭代器。元素被重复了多少次,在该迭代器中就包含多少个该元素。所有元素按照字母序排序,个数小于1的元素不被包含。
import collections
c = collections.Counter('adjsdkskdjksjaksklklakl')
sorted(c.elements())
返回结果:['a', 'a', 'a', 'd', 'd', 'd', 'j', 'j', 'j', 'k', 'k', 'k', 'k', 'k', 'k', 'k','l', 'l', 'l', 's', 's', 's', 's']

计数值的访问与缺失的键

功能:默认将计数器中所有的字符认为一个键,然后统计键出现的次数,即键值。如果键不存在则返回0.
import collections
c = collections.Counter('adjsdkskdjksjaksklklakl')
>>> c['a']
3
>>> c['b']
0
>>> c['l']
3

update && subtract

功能:都是更新计数器,update是增加,subtract是减少
import collections
>>> c = collections.Counter('which')
>>> c['h']  #这里的h出现2次
2
>>> c.update('with')
>>> c
Counter({'h': 3, 'i': 2, 'w': 2, 't': 1, 'c': 1})
>>> c['h'] #这里则完成了update操作,h出现了3次
3

>>> c.subtract('with') 
>>> c
Counter({'h': 2, 'c': 1, 'i': 1, 'w': 1, 't': 0})
>>> c['h'] #这里完成subtract操作之后,h出现的次数又恢复到2次
2

del

功能:删除键
import collections
>>> c = collections.Counter('which')
>>> c['h']  #这里的h出现2次
2
>>> del c['h']
>>> c
Counter({'c': 1, 'i': 1, 'w': 1, 't': 0})
>>> c['h']  #del操作删除了键'h'
0

copy

功能:浅拷贝
import collections
>>> c = collections.Counter('which')
>>> d = c.copy()
>>> d
Counter({'h': 2, 'c': 1, 'i': 1, 'w': 1})
>>> id(c)
7150792
>>> id(d)
6511976

算术和集合操作

功能:+、-、&、|操作也可以用于Counter。其中&和|操作分别返回两个Counter对象各元素的最小值和最大值。需要注意的是,得到的Counter对象将删除小于1的元素。

常用操作

说明:Counter继承dict的所有方法,常用的操作列在下面,仅供参考

有序字典orderedDict

有序字典继承字典的一切属性,只是在顺序上是有序的。
d = collections.OrderedDict({'name':'swht','age':18})
print(d)
返回结果:OrderedDict([('name', 'swht'), ('age', 18)])
print(type(d))
返回结果:<class 'collections.OrderedDict'>

move_to_end

功能:将指定的键值对从开头移动到末尾。
d = collections.OrderedDict({'name':'swht','age':18,'address':'shandong',})
d.move_to_end('name')
print(d)
返回结果:OrderedDict([('age', 18), ('address', 'shandong'), ('name', 'swht')])

pop

功能:移除字典键值,并返回删除键值的values
d = collections.OrderedDict({'name':'swht','age':18,'address':'shandong',})
d.pop('address')
print(d)
返回结果:OrderedDict([('age', 18), ('name', 'swht')])

clear

功能:清空有序字典的值
d = collections.OrderedDict({'name':'swht','age':18,'address':'shandong',})
d.clear()
print(d)
返回结果:OrderedDict()

keys,values,items

功能:继承字典的属性,获取字典的所有键和所有值
d = collections.OrderedDict({'name':'swht','age':18,'address':'shandong',})
l1 = d.keys()
l2 = d.values()
l3 = d.items()
print(l1,l2,l3)
返回结果:odict_keys(['address', 'age', 'name']) odict_values(['shandong', 18, 'swht']) odict_items([('age', 18), ('name', 'swht'), ('address', 'shandong')])

默认字典defaultdict

defaultdict是对字典的类型的补充,他默认给字典的值设置了一个类型。创建一个默认字典,value值类型为列表.
dic = collections.defaultdict(list)

可命名元组nametuple

没有现成的类,用户需要自行创建相应的类

测试代码

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import collections
MytupleClass = collections.namedtuple("MytupleClass",['x','y','z'])
obj = MytupleClass(11,22,33)
print(obj.x,obj.y,obj.z)
返回结果:11 22 33
总结:相当于在元组的基础上增加一个key,使其成为一个类字典的样子

队列

双向队列

下面两种方法都可以创建双向列表,虽然在最初的引用的类不同,但最后创建的类型 都是collections.deque
#创建双向队列
import collections
d = collections.deque()
返回结果:<class 'collections.deque'>

#but这样创建双向队列呢
import queue
p = queue.deque()
print(type(p))
#<class 'collections.deque'>

单向队列

#创建单向队列
import queue
q = queue.Queue()
print(type(q))
#<class 'queue.Queue'>

三、深浅拷贝

博客链接:http://www.cnblogs.com/songqingbo/p/5139015.html

#对于 数字 和 字符串 而言,赋值、浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址
    import copy
    a1 = 22255
    a2 = 22255
    print(id(a1),id(a2)) #3428240 3428240

#对于字典、元祖、列表 而言,进行赋值、浅拷贝和深拷贝时,其内存地址的变化是不同的。

    import copy
    #字典
    n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
    ##赋值
    n2 = n1
    print(n1,n2) #{'k1': 'wu', 'k2': 123, 'k3': ['alex', 456]} {'k1': 'wu', 'k2': 123, 'k3': ['alex', 456]}
    print(id(n1),id(n2))  #6674440 6674440 #内存地址一样
    ##浅拷贝
    n3 = copy.copy(n1)
    print(n1,n3) #{'k1': 'wu', 'k2': 123, 'k3': ['alex', 456]} {'k1': 'wu', 'k2': 123, 'k3': ['alex', 456]}
    print(id(n1),id(n3)) #6936584 12067848  #浅拷贝第一级,内存地址相同
    print(id(n1['k3']),id(n3['k3'])) #18741768 18741768
    ##深拷贝
    n4 = copy.deepcopy(n1)
    print(n1,n4) #{'k3': ['alex', 456], 'k2': 123, 'k1': 'wu'} {'k3': ['alex', 456], 'k1': 'wu', 'k2': 123}
    print(id(n1),id(n4)) #6805512 11736904
    print(id(n1['k3']),id(n4['k3'])) #7601032 7599496 #深拷贝第二级,内存地址也不相同

    #列表
    n1 = [1,2,3,4,5,[6,7],]
    ##赋值
    n2 = n1
    print(n1,n2) #[1, 2, 3, 4, 5, [6, 7]] [1, 2, 3, 4, 5, [6, 7]]
    print(id(n1),id(n2)) #18609928 18609928
    print(id(n1[5]),id(n2[5])) #18609544 18609544
    ##浅拷贝
    n3 = copy.copy(n1)
    print(n1,n3) #[1, 2, 3, 4, 5, [6, 7]] [1, 2, 3, 4, 5, [6, 7]]
    print(id(n1),id(n3)) #18609928 18232904
    print(id(n1[5]),id(n3[5])) #18609544 18609544
    ##深拷贝
    n4 = copy.deepcopy(n1)
    print(n1,n4) #[1, 2, 3, 4, 5, [6, 7]] [1, 2, 3, 4, 5, [6, 7]]
    print(id(n1),id(n4)) #18609928 18611848
    print(id(n1[5]),id(n4[5])) #18609544 18611912


    #元组
    一个小插曲:
        import copy
        n1 = (1,2,3,4,5,(6,7,),)
        #赋值
        n2 = n1
        print('n1:',n1,'n2:',n2) #n1: (1, 2, 3, 4, 5, (6, 7)) n2: (1, 2, 3, 4, 5, (6, 7))
        print(id(n1),id(n2)) #10416584 10416584
        print(id(n1[5]),id(n2[5])) #18415304 18415304
        print(type(n1),type(2)) #<class 'tuple'> <class 'int'>
        #浅拷贝
        n3 = copy.copy(n1)
        print('n1:',n1,'n3:',n3) #n1: (1, 2, 3, 4, 5, (6, 7)) n2: (1, 2, 3, 4, 5, (6, 7))
        print(id(n1),id(n3)) #10416584 10416584
        print(id(n1[5]),id(n3[5])) #18415304 18415304
        print(type(n1),type(3)) #<class 'tuple'> <class 'int'>
        #深拷贝
        n4 = copy.deepcopy(n1)
        print('n1:',n1,'n4:',n4) #n1: (1, 2, 3, 4, 5, (6, 7)) n2: (1, 2, 3, 4, 5, (6, 7))
        print(id(n1),id(n4)) #10416584 10416584
        print(id(n1[5]),id(n4[5])) #18415304 18415304
        print(type(n1),type(5)) #<class 'tuple'> <class 'int'>

再一个小插曲:
    import copy
    n1 = (1,2,3,4,5,[6,7,],)
    #赋值
    n2 = n1
    print('n1:',n1,'n2:',n2) #(1, 2, 3, 4, 5, [6, 7]) n2: (1, 2, 3, 4, 5, [6, 7])
    print(id(n1),id(n2)) #11465160 11465160
    print(id(n1[5]),id(n2[5])) #18480456 18480456
    print(type(n1),type(2)) #<class 'tuple'> <class 'int'>
    #浅拷贝
    n3 = copy.copy(n1)
    print('n1:',n1,'n3:',n3) #n1: (1, 2, 3, 4, 5, [6, 7]) n3: (1, 2, 3, 4, 5, [6, 7])
    print(id(n1),id(n3)) #11465160 11465160
    print(id(n1[5]),id(n3[5])) #18480456 18480456
    print(type(n1),type(3)) #<class 'tuple'> <class 'int'>
    #深拷贝
    n4 = copy.deepcopy(n1)
    print('n1:',n1,'n4:',n4) #n1: (1, 2, 3, 4, 5, [6, 7]) n4: (1, 2, 3, 4, 5, [6, 7])
    print(id(n1),id(n4)) #11465160 18109736
    print(id(n1[5]),id(n4[5])) #18480456 18478920
    print(type(n1),type(5)) #<class 'tuple'> <class 'int'>


出现以上问题有可能跟下面的说法有关:

案例代码

    import copy
    dic = {
        "cpu":[80,],
        "mem":[80,],
        "disk":[80,],
    }

    print("old:",dic)
    new_dic1 = copy.copy(dic)
    new_dic1["cpu"][0] = 50
    print("old:",dic)
    print("浅拷贝:",new_dic1)
    #返回结果:
    #old: {'disk': [80], 'cpu': [80], 'mem': [80]}
    #浅拷贝: {'disk': [80], 'cpu': [50], 'mem': [80]}

    new_dic2 = copy.deepcopy(dic)
    new_dic2["cpu"][0] = 60
    print("old:",dic)
    print("深拷贝:",new_dic2)
    #返回结果
    # old: {'mem': [80], 'cpu': [50], 'disk': [80]}
    # 深拷贝: {'mem': [80], 'cpu': [60], 'disk': [80]}

四、函数

博客链接:http://www.cnblogs.com/songqingbo/p/5142957.html

定义:

    #!/usr/local/env python3
    '''
    Author:@南非波波
    Blog:http://www.cnblogs.com/songqingbo/
    E-mail:qingbo.song@gmail.com
    '''
    #定义函数,作用打印一个值
    def num_print():
        n = 456
        n += 1
        print(n)
使用:

    #函数调用
    num_print()
    #将f变量指向函数num_print,然后调用f()相当于调用num_print()
    f = num_print
    f()

参数

形参:函数中一个变量,在函数执行前无意义,在函数调用时必须指定实际参数。
实参:实际参数用户传递给所调用的函数的一个变量,其值赋值到函数中的形式参数,然后在函数中       作为变量参与函数执行
默认参数:必须放在最后
    def show(a1,a2,a3 = 5):
        print(a1,a2,a3)
    show("wu","ha")
    #返回结果:wu ha 5

指定参数:
    def show(a1,a2):
        print(a1,a2)
    show(a2=52,a1=8)
    #返回结果:8 52

动态参数:
    *arg --序列:自动转换成一个元组
        def show(*arg):
            print(arg,type(arg))
        show(23,45,67)
        #返回结果:(23, 45, 67) <class 'tuple'>
        #or
        l = [23,45,67]
        show(*l)
        #返回结果:(23, 45, 67) <class 'tuple'>

    **arg --字典:自动转换成一个字典
        #默认字典处理
        def show(**arg):
            print(arg,type(arg))
        show(name1='swht',name2='shen')
        #返回结果:{'name1': 'swht', 'name2': 'shen'} <class 'dict'>
        #or
        d = {"name1"="swht","name2"="shen"}
        show(**d)
        #返回结果:{'name1': 'swht', 'name2': 'shen'} <class 'dict'>

    *arg,**kwarges --序列和字典
        def show(*args,**kwargs):
            print(args,type(args),'\n',kwargs,type(kwargs))
        show(23,45,67,82,name1='swht',name2='shen')
        #返回结果:(23, 45, 67, 82) <class 'tuple'> 
                   {'name2': 'shen', 'name1': 'swht'} <class 'dict'>        
        注意:使用*arg,**kwarges组合参数,必须是*arg在前,**kwarges在后,否则系统报错;另外实参在输入的时候也应该是按照上述顺序。

拓展:

def show(*args,**kwargs):
    print(args,type(args),'\n',kwargs,type(kwargs))
l = [23,45,67,82]
d = {'name1':'swht','name2':'shen'}
show(l,d)
#返回结果:
([23, 45, 67, 82], {'name1': 'swht', 'name2': 'shen'}) <class 'tuple'> 
{} <class 'dict'>

def show(*args,**kwargs):
    print(args,type(args),'\n',kwargs,type(kwargs))
l = [23,45,67,82]
d = {'name1':'swht','name2':'shen'}
show(*l,**d)
#返回结果:
(23, 45, 67, 82) <class 'tuple'> 
{'name2': 'shen', 'name1': 'swht'} <class 'dict'>

总结:
    函数可以传递元组、列表、字典等类型的值,由于带'*'、'**'的参数允许传入多个参数,所以在调用函数的时候默认将传入的参数识别到第一个*args。为了指定将参数传给某个args,这里需要对实参进行加'*'进行标识。

#list
show = "Welcome to {0},there have too many {1}!"
# reault = show.format("China","Foods")
l = ["China","Foods"]
reault = show.format(*l)
print(reault)
#返回结果:Welcome to China,there have too many Foods!

#dict
show = "{name} is a {acter}!"
# reault = show.format(name='swht',acter='teacher')
d = {'name':'swht','acter':'teacher'}
reault = show.format(**d)
print(reault)
#返回结果:swht is a teacher!

lambda表达式

    功能:简单函数的表示方式
    func = lambda a:a+1
    函数名  关键字 形参:函数体
    创建形式参数a,函数内容为a+1,并将结果return
测试代码:
    f = lambda x:x + 1
    ret = f(4)
    print(ret)

内置函数

abs()

功能:取绝对值
>>> abs(5)
5
>>> abs(-85)
85

all(iterable)

功能:iterable所有的元素都为真,返回True,否则返回False
备注:为False的元素:0、''、False或者空,其他的为True
参数:iterable为可迭代对象
all的功能可以使用下面的函数进行理解:
    def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
测试代码:
    all('test,hh')
    返回值为:True
    >>> all(['a', 'b', 'c', 'd'])  #列表list,元素都不为空或0
    True
    >>> all(['a', 'b', '', 'd'])  #列表list,存在一个为空的元素
    False
    >>> all([0, 1,2, 3])  #列表list,存在一个为0的元素
    False              
    >>> all(('a', 'b', 'c', 'd'))  #元组tuple,元素都不为空或0
    True
    >>> all(('a', 'b', '', 'd'))  #元组tuple,存在一个为空的元素
    False
    >>> all((0, 1,2, 3))  #元组tuple,存在一个为0的元素
    False
    >>> all([]) # 空列表
    True
    >>> all(()) # 空元组
    True    

any(iterable)

功能:iterable中元素只要有一个元素为真,则返回True,否则返回False(即iterable中所有的元素为假才会返回False)
参数:iterable为可迭代对象
any的功能可以使用下面的函数进行理解:
def any(iterable):
   for element in iterable:
       if  element:
           return False
   return True
测试代码:
    >>> any([0,1,2,3]) #列表中仅有一个元素0为假,返回True
    True
    >>> any([' ', '  ', '', 0])
    True
    >>> any([0]) #列表中元素只有一个元素0,返回False
    False
    >>> any([0,''])
    False
    >>> any([0,'',4])
    True    
    >>> any(('a', 'b', 'c', 'd'))  #元组tuple,元素都不为空或0
    True
    >>> any(('a', 'b', '', 'd'))  #元组tuple,存在一个为空的元素
    True
    >>> any((0, '', False))  #元组tuple,元素全为0,'',false
    False
    >>> any([]) # 空列表
    False
    >>> any(()) # 空元组
    False

map(iterable)

功能:对可迭代函数'iterable'中的每一个元素应用‘function’方法,将结果作为list返回
参考链接:http://segmentfault.com/a/1190000000322433
测试代码:
    def add_100(num):
        return num + 100
    li1 = [25,26,27]
    ret = list(map(add_100,li1))
    print(ret)
    返回结果:[125, 126, 127]


python2.7                                python3.5
两个版本的对比,真是让人感到诧异,python3上执行map明明已经获取了值,但非得加个list进行展示,超乎寻常。

def abc(a,b,c):
    return a*1000 + b*100 + c*10

list1 = [11,22,33]
list2 = [44,55,66]
list3 = [77,88,99]
ret = list(map(abc,list1,list2,list3))
print(ret) #返回结果 [16170, 28380, 40590]

ascii(object)

功能:该函数与python2中的repr()函数一样,返回一个可打印的对象字符串。当遇到非ascii码时,就会输出\x,\u或\U等字符来表示。例如:ascii(4) = int.__repr__(4) = repr(4)等号两边的方式是对等的。
测试代码:
    >>> ascii(54)
    '54'
    >>> ascii('o')
    "'o'"
    >>> type(ascii(54))
    <class 'str'>    
    >>> print(ascii(10), ascii(9000000), ascii('b\31'), ascii('0x\1000'))
        10 9000000 'b\x19' '0x@0'

bin()

功能:将整数转换为二进制字符串
>>> bin(56)
'0b111000'
>>> bin(100)
'0b1100100'
注意:如果bin()函数的实际参数不是一个整数,则该该实参(由类创建的对象)返回值必须是整数型
如:
>>> class myType:
...     def __index__(self):
...             return 56
...
>>> myvar = myType()
>>> bin(myvar)
'0b111000'

bool()

功能:获取对象的bool值
bool(0) #False
bool(5) #True
bool('') #False
#为假的元素:0 none 空列表 空字典 空元组 空字符串

bytearray()

功能:转成字符字典。Bytearray类型是一个可变的序列,并且序列中的元素的取值范围为 [0 ,255]。
>>> a = bytearray([5,8])
>>> a[0]
5
>>> a[1]
8
>>> a
bytearray(b'\x05\x08')

bytes()

    功能:返回一个新的数组对象,这个数组不能对数组元素进行修改,每个元素的取值范围为[0 ,255]
    测试代码:
    bytes(iterable_of_ints) 
        >>> b = bytes((5,8,6,8))
        >>> print(b)
        b'\x05\x08\x06\x08'
    bytes(string, encoding[, errors])     
        >>> bytes('sdjsd',encoding='utf-8')
        b'sdjsd'
    bytes(bytes_or_buffer)  ?
    bytes(int) 
        >>> bytes(5)
        b'\x00\x00\x00\x00\x00'
    bytes()  
        >>> bytes()
        b''

总结:(参考:http://blog.csdn.net/caimouse/article/details/40860827)
    bytes函数与bytearray函数主要区别是bytes函数产生的对象的元素不能修改,而bytearray函数产生的对象的元素可以修改。因此,除了可修改的对象函数跟bytearray函数不一样之外,其它使用方法全部是相同的。最后它的参数定义方式也与bytearray函数是一样的。

callable()

功能:判断函数或者对象是否可执行
>>> callable(5)
False
>>> callable(0)
False
>>> callable('')
False
>>> callable(int())
False
>>> callable(lambda x:x+1)
True

chr()

功能:参数为一个整型数字,返回值对应ASCII码的字符
>>> chr(5)
'\x05'
>>> chr(115)
's'
>>> chr(56)
'8'

ord()

功能:返回一个字符的ASCII码值
>>> ord('s')
115
>>> ord('5')
53

classmethod()

功能:classmethod是用来指定一个类的方法为类方法,没有此参数指定的类的方法为实例方法
    >>> class C: #定义一个类
    ...     @classmethod  #声明为类方法,不经过实例化就可以直接调用
    ...     def f(self): #定义一个函数(类的方法)
    ...             print "This is a class method"
    ...
    >>> C.f()  #通过类调用函数
    This is a class method
    >>> c = C()
    >>> c.f()
    This is a class method
    >>> class D:
    ...     def f(self):
    ...             print " This is not a class method "
    ...
    >>> D.f()  #没有经过@classmethod 声明的类方法,必须经过实例化才能被调用
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unbound method f() must be called with D instance as first argument (got nothing instead)
    >>> d = D()
    >>> d.f()
    This is not a class method

staticmethod()

    功能:类的静态方法,只能在类内部使用。经过静态类方法声明的类,在调用的时候不需要进行实例化

总结:对比classmethod()和staticmethod()

    静态方法:@staticmethod()
        class Foo(object):
            str = "I'm a static method."
            def bar():
                print(Foo.str)
            bar = staticmethod(bar)

        Foo.bar()
    返回结果:I'm a static method. 

    类方法:@classmethod()
        class Foo(object):
            str = "I'm a static method."
            def bar(cls):
                print(cls.str)
            bar = classmethod(bar)
        Foo.bar()
    返回结果:I'm a static method. 
较简单的操作代码:

    静态方法:@staticmethod()
        class Foo:
            str = "I'm a static method."
            @staticmethod
            def bar():
                print(Foo.str)
        Foo.bar() 
    返回结果:I'm a static method. 

    类方法:@classmethod()
        class Foo:
            str = "I'm a static method."
            @classmethod
            def bar(cls):
                print(cls.str )
        Foo.bar()
    返回结果:I'm a static method.

compile()、eval()、exec()

功能:compile语句是从type类型中将str里面的语句创建成代码对象。
    compile语句的目的是提供一次性的字节码编译,就不用在以后的每次调用中重新进行编译了
语法:compile( str, file, type )
    eveal_code = compile('1+2','','eval')
    >>>eveal_code
    返回结果:<code object <module> at 0x01555D40, file "", line 1>
    >>>eval(eveal_code)
    返回结果:3

    single_code = compile( 'print("apicloud.com")', '', 'single' )
    >>> single_code
    返回结果:<code object <module> at 0x01555B10, file "", line 1>
    >>> exec(single_code)
    返回结果:apicloud.com

complex()

功能:创建一个值为real + imag * j的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。
参数real: int, long, float或字符串;
参数imag: int, long, float
>>>complex()
0j
#数字
>>> complex(1,2)
(1+2j)
#当做字符串处理
>>> complex('1')
(1+0j)
#注意:这个地方在“+”号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错
>>> complex('1+2j')
(1+2j)

delattr()

参考链接:http://www.cnblogs.com/zhangjing0502/archive/2012/05/16/2503702.html
功能:删除object对象名为name的属性
语法:delattr(object,name) 
参数object:对象。
参数name:属性名称字符串。

>>> class Person:
...     def __init__(self, name, age):
...             self.name = name
...             self.age = age
...
>>> tom = Person("Tom", 35)
>>> dir(tom)
['__doc__', '__init__', '__module__', 'age', 'name']
>>> delattr(tom, "age")
>>> dir(tom)
['__doc__', '__init__', '__module__', 'name']

getattr()

功能:用于返回一个对象属性,或者方法
class A:   
    def __init__(self):   
        self.name = 'zhangjing'  
    #self.age='24'
    def method(self):   
        print("method print")  

Instance = A()   
print(getattr(Instance , 'name', 'not find')) #如果Instance 对象中有属性name则打印self.name的值,否则打印'not find'
print(getattr(Instance , 'age', 'not find'))  #如果Instance 对象中有属性age则打印self.age的值,否则打印'not find'
print(getattr(a, 'method', 'default'))  
#如果有方法method,否则打印其地址,否则打印default   
print(getattr(a, 'method', 'default')()) 
#如果有方法method,运行函数并打印None否则打印default

li=["swht","shen"]
getattr(li,"pop")
返回结果:<built-in method pop of list object at 0x01AFDA80>

setattr()

功能:参数是一个对象,一个字符串和一个任意值。字符串可能会列出一个现有的属性或一个新的属性。这个函数将值赋给属性的。该对象允许它提供。
语法:setattr(object, name, value)    
setattr(x,“foobar”,123)相当于x.foobar = 123

hasattr()

功能:用于确定一个对象是否具有某个属性
语法:hasattr(object, name) -> bool
    判断object中是否有name属性,返回一个布尔值
li=["swht","shen"]
hasattr(li,'append')
返回结果:True

dict()

功能:字典定义函数,可以创建一个字典,也可以将其他类型(列表、元组、字符串)转换成字典类型
定义:
    dict1 = dict(one = 1, two = 2, a = 3)
    prin(dict1)
    {'one': 1, 'a': 3, 'two': 2}
类型转换:
    list1 = ['name','age',]
    list2 = ['swht',18]
    dict(zip(list1,list2))
    返回结果:{'name': 'swht', 'age': 18}

    new_list= [['key1','value1'],['key2','value2'],['key3','value3']]
    dict(new_list)
    返回结果:{'key3': 'value3', 'key1': 'value1', 'key2': 'value2'}

dir()

功能:查看函数或模块内的操作方法都有什么,输出的是方法列表。
如dir(int)可以直接获取int的所有方法,返回的类型是一个列表

divmod()

功能:divmod(a,b)方法返回的是a//b(除法取整)以及a对b的余数
>>> divmod(2,5)
(0, 2)
>>> divmod(12,5)
(2, 2)

enumerate()

功能:获取字典的索引值并指定开始值
li = ['swht','shen','test']
for i,k in enumerate(li,3): #遍历列表,索引值从3开始
    print(i,k)
#返回结果
3 swht
4 shen
5 test

filter()

参考链接:http://www.cnblogs.com/fangshenghui/p/3445469.html
功能:filter(function, sequence)对于队列中的item依次被function处理
def fun(item):
    if item != 4:
        return item
list1 = [5,4,8]
print(list(filter(fun,list1)))
返回结果:[4, 8]
总结:相当于一个过滤函数

frozenset()

参考:http://blog.csdn.net/caimouse/article/details/42042051
功能:本函数是返回一个冻结的集合
l = [1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 9]  
print(len(l), l)  
set = frozenset(l)  
print(len(set), set) 
返回结果:11 [1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 9]
         9 frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9})
总结:所谓冻结就是这个集合不能再添加或删除任何集合里的元素。因此与集合set的区别,就是set是可以添加或删除元素,而frozenset不行。frozenset的主要作用就是速度快,它是使用hash算法实现。参数iterable是表示可迭代的对象,比如列表、字典、元组等等

locals()、globals()

功能:基于字典的访问局部和全局变量的方式
locals 是只读的,globals 不是
关于名字空间的相关说明请移步参考:http://blog.csdn.net/scelong/article/details/6977867

hash()

功能:输出对象的hash值
>>> hash(8)
8
>>> hash('sd')
-584109415
>>> hash('99')
-1356598271
>>> hash('asds')
-1179125483

help()

功能:查看函数或模块用途的详细说明
使用方法:help(object)

类型转换

int(x [,base ])         将x转换为一个整数    
long(x [,base ])        将x转换为一个长整数    
float(x )               将x转换到一个浮点数    
complex(real [,imag ])  创建一个复数    
str(x )                 将对象 x 转换为字符串    
repr(x )                将对象 x 转换为表达式字符串    
eval(str )              用来计算在字符串中的有效Python表达式,并返回一个对象    
tuple(s )               将序列 s 转换为一个元组    
list(s )                将序列 s 转换为一个列表    
chr(x )                 将一个整数转换为一个字符    
unichr(x )              将一个整数转换为Unicode字符    
ord(x )                 将一个字符转换为它的整数值    
hex(x )                 将一个整数转换为一个十六进制字符串    
oct(x )                 将一个整数转换为一个八进制字符串

id()

功能:获取对象的内存地址
id(object)

input()

功能:获取用户的输入信息
input("请输入你的名字:")
>>>请输入你的名字:swht
swht

isinstance()

功能:判断对象类型
isinstance(5,int)
返回结果:True

issubclass()

功能:本函数用来判断类参数class是否是类型参数classinfo的子类
class Line:  
    pass  
class RedLine(Line):  
    pass  

class Rect:  
    pass  

print(issubclass(RedLine, Line))  #返回True  Redline是Line的子类
print(issubclass(Rect, Line))  #返回False  

iter()

功能:创建一个迭代器
for i in iter((1,2,4,5,6,7,)):
    print(i)
返回结果:1 2 4 5 6 7 #循环遍历元组

len()

功能:获取字符串的长度
len(str)

max()

功能:返回所有整数中最大的一个数
max(5,6,8,7) 
返回结果:8

memoryview()

功能:本函数是返回对象obj的内存查看对象
>>> v = memoryview(b'abc123')
>>> print(v[1])
98
>>> print(v[0])
97
>>> print(v[2])
import struct  
buf = struct.pack("i"*12, *list(range(12)))  
x = memoryview(buf)  
y = x.cast('i', shape=[2,2,3])  
print(y.tolist()) 
返回结果:[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]

总结:所谓内存查看对象,就是对象符合缓冲区协议的对象,为了给别的代码使用缓冲区里的数据,而不必拷贝,就可以直接使用。参考链接:http://blog.csdn.net/caimouse/article/details/43083627

sorted()

功能:排序
sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]

sum()

功能:返回整数数字的和
sum([1,5,8]) #参数是一个list
返回结果:14

super()

功能:用来解决多重继承问题

type()

功能:获取对象的类型
type(object)

vars()

功能:本函数是实现返回对象object的属性和属性值的字典对象
>>> class Foo:
...     a = 1
...
>>> print(vars(Foo))
{'a': 1, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__doc__': None, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__module__': '__main__'}

总结:如果默认不输入参数,就打印当前调用位置的属性和属性值,相当于locals()的功能。如果有参数输入,就只打印这个参数相应的属性和属性值。参考:http://blog.csdn.net/caimouse/article/details/46489079

zip()

功能:zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表
>>> x = [1,2,3,]
>>> y = [4,5,6,]
>>> z = [7,8,9,]
>>> xyz = zip(x,y,z)
>>> print(xyz)
<zip object at 0x00FBD968>
>>> print(list(xyz))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

random

功能:产生随机数
import random
random.randint(1,99) #从1-99中产生随机数

import()

功能:查看模块所在的位置
 __import__('random') #参数为一个字符串
<module 'random' from 'D:\\Program Files\\Python\\Python35\\python35.zip\\random.pyc'>

open()函数

博客参考:http://www.cnblogs.com/songqingbo/p/5102618.html

read()

功能:读取文件中的所有内容,返回的类型是字节

readline()

功能:读取文件中的一行数据。返回的类型是字节

readlines()

功能:读取文件中的所有内容,返回的类型是list

tell()

功能:查看当前指针位置,返回值类型为整数

seek()

功能:指定当前指针位置


files = open('test.txt','r',encoding='utf-8')
files.seek(5)
print(files.read()) #读取指为直接切割针5后面的所有字符
files.truncate() #获取指针5之前的所有字符然后写到原来的文件(或者可以理解)
files.close()

扩展

读二进制文件:

    input = open('data','rb')

读取所有内容:

    f = open('test.txt','r')
    try:
        all_txt_view = f.read()
    finally:
        f.close()

读取固定字节:

    f = open('test.txt','rb')
    try:
        while True:
            chunk = f.read(100)
            if not chunk:
                break
            pass
    finally:
        f.close()

读每行:

    list_of_all_the_lines = f.readlines()

如果文件是文本文件,还可以直接遍历文件对象获取每行:

    for line in f:
        print(line)

写文件写文本文件

    output = open('data','w')

写入多行:

    f.writeline(list_of_text_string)

作业:

作业连接:http://www.cnblogs.com/wupeiqi/articles/4950799.html
1. 用户输入一个字符串,将其转换成字典 使用json
2. 增加一条记录
3. (可选)删除一条
4. (可选)线上文件修改


global       
        log 127.0.0.1 local2
        daemon
        maxconn 256
        log 127.0.0.1 local2 info
defaults
        log global
        mode http
        timeout connect 5000ms
        timeout client 50000ms
        timeout server 50000ms
        option  dontlognull

listen stats :8888
        stats enable
        stats uri       /admin
        stats auth      admin:1234

frontend oldboy.org
        bind 0.0.0.0:80
        option httplog
        option httpclose
        option  forwardfor
        log global
        acl www hdr_reg(host) -i www.oldboy.org
        use_backend www.oldboy.org if www

backend test.oldboy.org
        server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
        #server 100.1.7.9 100.1.7.999 weight 20 maxconn 3000


backend buy.oldboy.org
        server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000

字典:        
{"backend": "test.oldboy.org",
 "record":{
        "server": "100.1.7.999",
        "weight": 20,
        "maxconn": 30
  }
}
文章目录
  1. 一、set集合
  2. 二、collection系列
    1. Counter
    2. 有序字典orderedDict
    3. 默认字典defaultdict
    4. 可命名元组nametuple
    5. 队列
  3. 三、深浅拷贝
  4. 四、函数
    1. 参数
    2. lambda表达式
    3. 内置函数
    4. open()函数
    5. 作业: