python常见使用技巧

来源:互联网 发布:nginx apache php性能 编辑:程序博客网 时间:2024/06/07 19:35

1.python断言,可以很好的找到某一个出错的地方

#-*- coding:utf-8 *-*- 2  3 __metaclass__ = type 4  5  6 #断言 7 def demo(): 8     a = 5 9     assert a == 510     assert a == 4,'a不等于5'11     print 'normal done'12 demo()

这里写图片描述

2.python内建的call函数,可以让类的实例像函数一样使用

1 #内建 __call__ 函数学习2 class demo2:3     def __call__(self,*args):4         print args5 a = demo2()6 a(10)

这里写图片描述

3.python属性的创建

 1 #属性创建 2 class demo3: 3     def __init__(self,width,height): 4         self.width = width 5         self.height = height 6     def setSize(self,size): 7         self.width,self.height = size 8     def getSize(self): 9         return self.width,self.height10     size = property(getSize,setSize)  #顺序不能变(get,set,del,doc)11 12 r = demo3(10,20)13 r.size = (20,20)14 print r.size

这里写图片描述

4.python迭代器,以斐波那契数列为例

 1 #斐波那契数列迭代器 2 class fibs: 3     def __init__(self): 4         self.a = 0 5         self.b = 1 6  7     def next(self):   #python3.x中用 __next__实现,使用时用next(f) 8         self.a, self.b = self.b, self.a+self.b 9         return self.a10 11     def __iter__(self):  #返回一个迭代器12         return self13 14 f = fibs()15 for i in range(10):16     print f.next()

这里写图片描述

5.python中lambda函数使用

1 #lambda生成斐波那契数列2 print reduce(lambda x,y:x+y,range(11))

6.python零填充n.zfill(x)

n = '1'print n.zfill(5)  #一共有5位,不够的前面用0填充#输出:>>>'00001'
原创粉丝点击