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

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

#带索引的遍历
for index, value in enumerate(range(, )):
print(index, value) #好用的zip方法
for x, y in zip(range(, ), range(, )):
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()
inner_func()
inner_func() #函数作为对象
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', )
    super(AccessCounter, self).__setattr__('value', value) def __setattr__(self, name, value):
    if name == 'value':
    super(AccessCounter, self).__setattr__('counter', self.counter + )
    # 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 + )
    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+
hh = [,,] map(add100,hh)
#---[, , ]
 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

python 补缺收集的更多相关文章

  1. Python零散收集:

    Python零散收集 转义字符 描述 \(在行尾时) 续行符 \\ 反斜杠符号 \’ 单引号 \” 双引号 \a 响铃 \b 退格(Backspace) \e 转义 \000 空 \n 换行 \v 纵 ...

  2. python信息收集之子域名

    python信息收集之子域名 主要是以下3种思路: 字典爆破 搜索引擎 第三方网站 0x00 背景知识 list Python内置的一种数据类型是列表:list是一种有序的集合. >>&g ...

  3. [转]Python 模块收集

    Python 模块收集 转自:http://kuanghy.github.io/2017/04/04/python-modules Python | Apr 4, 2017 | python 工具 a ...

  4. 学习Linux系列--Python资源收集

    本系列文章记录了个人学习过程的点点滴滴. 回到目录 玩Linux,不懂一门脚本语言是不行的,我这里选择的是Python. 10.入门资源 下面前三遍是比较系统的文档,后面是一些心得,我看了好几天,终于 ...

  5. Python脚本收集腾讯云CDN日志,并入ELK日志分析

    负责搭建公司日志分析,一直想把CDN日志也放入到日志分析,前些日志终于达成所愿,现在贴出具体做法: 1.收集日志 腾讯云CDN日志一般一小时刷新一次,也就是说当前只能下载一小时之前的日志数据,但据本人 ...

  6. python 黑魔法收集--已结

    awesome python 中文大全 Fabric , pip, virtualenv 内建函数好文 awesome python 奇技淫巧 一句话求阶乘 from functools import ...

  7. Python学习:python网址收集

    Python学习网址收集: 语法学习:http://www.cnblogs.com/hongten/tag/python/             http://www.liaoxuefeng.com ...

  8. python信息收集(一)

        在渗透测试初期,需要进行大量的信息收集.一般情况下,信息收集可以分为两大类----被动信息收集和主动信息收集.     其中,被动信息收集主要是通过各种公开的渠道来获取目标系统的信息,例如:站 ...

  9. python函数收集不确定数量的值

    python写函数的时候,有时候会不确定到底传入多少值. 首先是,*args,单星号参数收集参数: 1 #!usr/bin/python 2 #-*-coding:utf-8-*- 3 4 #定义一个 ...

随机推荐

  1. 使用imp命令和exp命令对oracle数据库进行导入导出操作

    命令说明 imp命令和exp命令需要在cmd命令窗口下执行,并且需要在系统环境变量中配置imp,exp命令所在目录 导出命令 --全库导出 exp system/systempassword@orcl ...

  2. 洛谷P1312 Mayan游戏

    P1312 Mayan游戏 题目描述 Mayan puzzle是最近流行起来的一个游戏.游戏界面是一个 7 行5 列的棋盘,上面堆放着一些方块,方块不能悬空堆放,即方块必须放在最下面一行,或者放在其他 ...

  3. 10分钟了解什么是BFC

    BFC对于已经是一个耳熟能详的词汇了,而且在前端面试中,这题也是一个高频题.虽然我们平时在开发的时候知道如何利用BFC来解决问题,但是我们要具体说出BFC的概念和怎么触发BFC,我相信很多小伙伴也是和 ...

  4. SP1716 GSS3

    题意翻译 \(n\) 个数,\(q\) 次操作 操作\(0\) \(x\) \(y\)把\(A_x\) 修改为\(y\) 操作\(1\) \(l\) \(r\)询问区间\([l, r]\)的最大子段和 ...

  5. UnityError 动画系统中anystate跳转重复播放当前动画解决方案

  6. centos6安装bochs

    安装包 bochs 2.6.8 平台 centos6 前提依赖 yum groupinstall -y "Server Platform Development" "De ...

  7. The program 'unzip' is currently not installed. You can install it by typing:

    linux解压遇到下面问题: The program 'unzip' is currently not installed. You can install it by typing: sudo ap ...

  8. 【转】sql server数据库操作大全——常用语句/技巧集锦/经典语句

    本文为累计整理,有点乱,凑合着看吧! ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆ ☆ ☆ ☆ sql 宝 典 ☆ ☆ ☆ 2012年-8月 修订版 ☆ ...

  9. 基于FCM的消息推送功能

    需求背景 我方项目需要支持客户端消息推送,iOS终端可以借由苹果本身的apns很方便的实现,但是对于Android来说,必须集成第三方的SDK来处理.考虑到项目需要以及成本,我们选择使用谷歌的FCM框 ...

  10. 映射部署tomcat

    近期遇到问题总结[映射部署]2017年10月03日 10:16:54 守望dfdfdf 阅读数:108更多个人分类: Java知识编辑版权声明:本文为博主原创文章,转载请注明文章链接. https:/ ...