您的位置:首页 > 编程语言 > Python开发

自学Python三 Python中的屠龙刀(续)

2016-01-12 16:37 453 查看
  装饰器:

  在函数代码功能运行期间动态增加功能的方式叫做装饰器(Decorator)。它对一个函数或者类进行再加工。

  我们先定义两个函数,一个计算两数和,一个计算两数差。

>>> def square_sum(a,b):
...     return a + b
...
>>> def square_diff(a,b):
...     return a - b
...
>>> print(square_sum(3,4))
7
>>> print(square_diff(9,5))
4


  如果我们想要给这个函数再加其他功能呢,如打印出输入的参数值,我们可能会这样:

>>> def square_sum(a,b):
...     print 'input:',a,b
...     return a + b
...
>>> print(square_sum(3,4))
input: 3 4
7


  在python中,我们可以利用装饰器这么干:

>>> def decorator(f):
...     def new_f(a,b):
...             print 'input',a,b
...             return f(a,b)
...     return new_f
...
>>> @decorator
... def square_sum(a,b):
...     return a + b
...
>>> @decorator
... def square_diff(a,b):
...     return a - b
...
>>> print(square_sum(3,4))
input 3 4
7
>>> print(square_diff(9,5))
input 9 5
4


  在上面的例子中,装饰器接受一个函数作为输入参数,并返回一个新的函数,装饰器新建了一个可用函数new_f,在这个函数中我们增加了打印功能,并通过调用之前的函数f来实现原来函数的功能。当我们在调用square_sum(3,4)的时候就等同于

  square_sum = decorator(square_sum)

  square_sum(3,4)

  这样的好处是提高了代码的可复用性!

  在上面的装饰器中,它默认他后面的函数是他的唯一参数,如果我们想传其他参数怎么办呢,比如@decorator(a),我们可以这样:

>>> def pre_str(pre=''):                #一层新函数
...     def decorator(f):                     #原来的装饰器
...             def new_f(a,b):
...                     print(pre + "input", a, b)
...                     return f(a,b)
...             return new_f
...     return decorator
...
>>> @pre_str('balabala')
... def square_sum(a,b):
...     return a+b
...
>>> print(square_sum(3,4))
('balabalainput', 3, 4)
7


  装饰类:

  一个装饰类可以接收一个类,并返回一个类,起到加工类的效果!

>>> def decorator(aClass):
...     class newClass:
...             def __init__(self,age):
...                     self.total_display = 0
...                     self.wrapped = aClass(age)
...             def display(self):
...                     self.total_display += 1
...                     print "total display",self.total_display
...                     self.wrapped.display()
...     return newClass
...
>>> @decorator
... class Bird:
...     def __init__(self,age):
...             self.age = age
...     def display(self):
...             print "My age is",self.age
...
>>> eagleLord = Bird(5)
>>> for i in range(3):
...     eagleLord.display()
...
total display 1
My age is 5
total display 2
My age is 5
total display 3
My age is 5


  生成器:

  生成器是为了避免构造一个超大的列表,是一边循环一边计算的机制!

>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x02140620>
>>> g.next()
0
>>> g.next()
1


  generator保存的是算法,每次都需要调用next来进行计算出下一个元素的值,是可迭代的,我们可以通过for来访问他。在函数中可以用yield进行中断输出!

  上下文管理器:

  用于规定某个对象的适用范围,类比于using(){} 在python中是 with...as...

# without context manager
f = open("new.txt", "w")
print(f.closed)               # whether the file is open
f.write("Hello World!")
f.close()
print(f.closed)

# with context manager
with open("new.txt", "w") as f:
print(f.closed)
f.write("Hello World!")
print(f.closed)


  上面两断代码执行的操作是一样的,通过with as 在超出范围之后自动进行了f的释放!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: