zoukankan      html  css  js  c++  java
  • python 补缺收集

    [http://www.cnblogs.com/happyframework/p/3255962.html]

    1. 高效code 与 不常用的函数用法:

    #带索引的遍历
    for index, value in enumerate(range(0, 10)):
        print(index, value)
    
    #好用的zip方法
    for x, y in zip(range(1, 10), range(1, 10)):
        print(x, y)
    # 收集多余的位置参数
    def func_with_collection_rest_parameters(x, y, *rest):
        print(x, y)
        print(rest)
    
    func_with_collection_rest_parameters(1, 2, 3, 4, 5)
    
    #收集命名参数
    def func_with_collection_rest_naned_parameters(*args, **named_agrs):
        print(args)
        print(named_agrs)
    
    func_with_collection_rest_naned_parameters(1, 2, 3, x = 4, y = 5, z = 6)
    
    #集合扁平化
    func_with_collection_rest_naned_parameters([1, 2, 3], {"x": 4, "y": 4, "z": 6}) #这会导致args[0]指向第一个实参,args[1]指向第二个实参。
    func_with_collection_rest_naned_parameters(*[1, 2, 3], **{"x": 4, "y": 4, "z": 6}) #这里的执行相当于func_with_collection_rest_naned_parameters(1, 2, 3, x = 4, y = 5, z = 6)。
    # python支持闭包
    def func(x):
        def inner_func(y):
            print(x + y)
    
        return inner_func
    
    inner_func = func(10)
    inner_func(1)
    inner_func(2)
    
    #函数作为对象
    def func(fn, arg):
        fn(arg)
    
    func(print, "hello")
    func(lambda arg : print(arg), "hello")

    2. 异常处理

    # coding=utf-8
    
    # 自定义异常
    class HappyException(Exception):
        pass
    
    # 引发和捕获异常
    try:
        raise HappyException
    except:
        print("HappyException")
    
    try:
        raise HappyException()
    except:
        print("HappyException")
    
    # 捕获多种异常
    try:
        raise HappyException
    except (HappyException, TypeError):
        print("HappyException")
    
    # 重新引发异常
    try:
        try:
            raise HappyException
        except (HappyException, TypeError):
            raise
    except:
        print("HappyException")
    
    #访问异常实例
    try:
        raise HappyException("都是我的错")
    except (HappyException, TypeError), e:
        print(e)
    
    #按类型捕获
    try:
        raise HappyException
    except HappyException:
        print("HappyException")
    except TypeError:
        print("TypeError")
    
    #全面捕获
    try:
        raise HappyException
    except:
        print("HappyException")
    
    #没有异常的else
    try:
        pass
    except:
        print("HappyException")
    else:
        print("没有异常")
    
    #总会执行的final
    try:
        pass
    except:
        print("HappyException")
    else:
        print("没有异常")
    finally:
        print("总会执行")

    3. 类:相关说明

       几个规则:

    1. 一切都是对象,python中一切都是对象,每个对象都包含一个__class__属性以标记其所属类型。
    2. 每个对象(记得一切都是对象啊)都包含一个__dict__属性以存储所有属性和方法。
    3. 每个类型都包含一个__bases__属性以标记其父类。
    4. 属性和方法的访问规则:依次搜索instance、子类、父类、父类的父类、直到object的__dict__,如果找到就返回。
    5. 属性和方法的设置规则:直接设置instance.__dict__。
    6. 以上属性和方法访问或设置规则没有考虑“魔法方法”

      “魔法方法” 详细内容参考:http://www.rafekettler.com/magicmethods.html

      对象构造相关:__new__、__init__、__del__。

    from os.path import join
    
    class FileObject:
        '''Wrapper for file objects to make sure the file gets closed on deletion.'''
    
        def __init__(self, filepath='~', filename='sample.txt'):
            # open a file filename in filepath in read and write mode
            self.file = open(join(filepath, filename), 'r+')
    
        def __del__(self):
            self.file.close()
            del self.file

    4. 运算符重载:所有运算符都能重载。

    class Word(str):
        '''Class for words, defining comparison based on word length.'''
    
        def __new__(cls, word):
            # Note that we have to use __new__. This is because str is an immutable
            # type, so we have to initialize it early (at creation)
            if ' ' in word:
                print "Value contains spaces. Truncating to first space."
                word = word[:word.index(' ')] # Word is now all chars before first space
            return str.__new__(cls, word)
    
        def __gt__(self, other):
            return len(self) > len(other)
    
        def __lt__(self, other):
            return len(self) < len(other)
    
        def __ge__(self, other):
            return len(self) >= len(other)
    
        def __le__(self, other):
            return len(self) <= len(other)
    
    print(Word("duan") > Word("wei"))

    属性访问:

    • class AccessCounter:
          '''A class that contains a value and implements an access counter.
          The counter increments each time the value is changed.'''
      
          def __init__(self, value):
              super(AccessCounter, self).__setattr__('counter', 0)
              super(AccessCounter, self).__setattr__('value', value)
      
          def __setattr__(self, name, value):
              if name == 'value':
                  super(AccessCounter, self).__setattr__('counter', self.counter + 1)
              # Make this unconditional.
              # If you want to prevent other attributes to be set, raise AttributeError(name)
              super(AccessCounter, self).__setattr__(name, value)
      
          def __delattr__(self, name):
              if name == 'value':
                  super(AccessCounter, self).__setattr__('counter', self.counter + 1)
              super(AccessCounter, self).__delattr__(name)
    • 5. Python lambda用法 [ lambda提供了一个运行时动态创建函数的方法]  

               1 python lambda会创建一个函数对象,但不会把这个函数对象赋给一个标识符,而def则会把函数对象赋值给一个变量。
               2 python lambda它只是一个表达式,而def则是一个语句。
       

    # lambda.py 
    def fun1(n): 
        return lambda m:m**n 
    def fun2(m, n):
        return m+n 
    # 演示通常的lambda用法
    f1 = lambda x,y,z: x*2+y+z 
    print f1(3,2,1) 
    # 动态生成一个函数 
    f2 = fun1(2) 
    print f2(4) 
    # lambda用作函数参数的写法 
    print fun2(3, (lambda x:x+1)(2))

    6. python中的map()函数 http://my.oschina.net/zyzzy/blog/115096

        map(functioniterable...)

        Apply function to every item of iterable and return a list of the results.

        If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended withNoneitems. If function isNone, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

    def add100(x):
        return x+100
    hh = [11,22,33]
    
    map(add100,hh)
    #---[111, 122, 133]
     def abc(a, b, c):
         return a*10000 + b*100 + c
     
     list1 = [11,22,33]
     list2 = [44,55,66]
     list3 = [77,88,99]
    map(abc,list1,list2,list3)
    #---[114477, 225588, 336699]
    如果给出了额外的可迭代参数,则对每个可迭代参数中的元素‘并行’的应用‘function’
    在每个list中,取出了下标相同的元素,执行了abc()。
    #如果'function'给出的是‘None’,自动假定一个‘identity’函数
    
    list1 = [11,22,33]
    map(None,list1)
    #---[11, 22, 33]
    
    list1 = [11,22,33]
    list2 = [44,55,66]
    list3 = [77,88,99]
    
    map(None,list1,list2,list3)
    #----[(11, 44, 77), (22, 55, 88), (33, 66, 99)]

    a
    =[1,2,3]
    b=[4,5,6]

    map(lambda x,y:x+y, a,b)
    #---[5,7,9]

     7.  序6:另外2个处理列表的函数:reduce & filter  http://jeffxie.blog.51cto.com/1365360/328207

    filter很容易理解用于过滤,map用于映射,reduce用于归并. 是python列表方法的三架马车。

    filter() 函数:  filter 函数的功能相当于过滤器。调用一个布尔函数bool_func来迭代遍历每个seq中的元素;返回一个使bool_seq返回值为true的元素的序列。

    a=[1,2,3,4,5,6,7]
    b=filter(lambda x:x>5, a)
    print b
    #---[6,7]

    如果filter参数值为None,就使用identity()函数,list参数中所有为假的元 素都将被删除。如下所示:

    a=[0,1,2,3,4,5,6,7]
    b=filter(None, a)
    print b
    #---[1,2,3,4,5,6,7]
    • reduce() 函数:

           reduce函数,func为二元函数,将func作用于seq序列的元素,每 次携带一对(先前的结果以及下一个序列的元素),连续的将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值。

    a = [1,2,3,4,5]
    reduce(lambda x,y:x+y,a)
    #---15
  • 相关阅读:
    使用yarn来替代npm
    React及Nextjs相关知识点小结
    appstore-react v2.0—redux-actions和redux-saga的应用
    开机SystemServer到ActivityManagerService启动过程分析
    java 读取气象专业格式NetCDF文件
    maven项目对于maven远程仓库没有资源的解决办法
    leaflet 使用kriging.js实现前端自定义插值
    leaflet 使用高德地图实例
    uni-app上使用leaflet地图的解决方案
    MySQL创建新用户并且赋予权限
  • 原文地址:https://www.cnblogs.com/xiaoxxy/p/3259732.html
Copyright © 2011-2022 走看看