python常见使用技巧

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

 1 #-*- coding:utf-8 *-*-
 2 
 3 __metaclass__ = type
 4 
 5 
 6 #断言
 7 def demo():
 8     a = 5
 9     assert a == 5
10     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 args
5 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.height
10     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.a
10 
11     def __iter__(self):  #返回一个迭代器
12         return self
13 
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))

执行结果

欢迎来邮件交流:lq65535@163.com
原文地址:https://www.cnblogs.com/lq1024/p/7642861.html