裝飾器
裝飾器本質上是一個Python函式,它可以讓其他函式在不需要做任何代碼變動的前提下增加額外功能,裝飾器的回傳值也是一個函式物件
它經常用于有切面需求的場景,比如:插入日志、性能測驗、事務處理、快取、權限校驗等場景,裝飾器是解決這類問題的絕佳設計,有了裝飾器,我們就可以抽離出大量與函式功能本身無關的代碼并繼續重用
1、函式呼叫
#定義一個函式
def hi(mes="我要玩亞索"):
return "中路是我的,"+mes
print(hi())
# 拷貝函式
greet = hi
print(greet())
try:
# 洗掉原函式
del hi
print(hi())
except Exception as e:
print("函式已被洗掉")
finally:
print(greet())
2、函式中呼叫函式
def hi(name="銳雯"):
print("now you are inside the hi() function")
def greet():
return "now you are inside the greet() function"
def welcone():
return "now you are inside the welcome() function"
print(greet())
print(welcone())
print("now you are back in the hi() function")
hi()
try:
# 在主函式中呼叫hi函式中的greet函式
greet()
except Exception as e:
print("函式不存在")
3、函式呼叫回傳函式呼叫
def hi(name="銳雯"):
def greet():
return "now you are inside the greet() function"
def welcome():
return "now you are inside the welcome() function"
if name=="銳雯":
return greet
else:
return welcome
a = hi()
print(a)
print(a())
a = hi("亞索")
print(a())
4、函式傳參–傳入函式引數
def hi():
return "It's a nice day"
def doSomethingToSee(func):
print(func())
print("I should do something")
doSomethingToSee(hi)
5、函式傳入函式引數回傳函式呼叫
def a_new_decorator(a_func):
def wrapTheFunction():
print("在函式呼叫前我正在做一些無聊的事情")
a_func()
print("終于結束函式呼叫了,我都快累死了")
return wrapTheFunction
def a_function_requiring_decoration():
print("我是一個需要裝飾的函式")
a_function_requiring_decoration()
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
a_function_requiring_decoration()
上面的函式a_new_decorator就是一個裝飾器
現在python允許裝飾器呼叫使用@語法糖
下面使用@語法糖重構上述裝飾器:
import functools
def a_new_decorator(a_func):
def wrapTheFunction():
print("在函式呼叫前我正在做一些無聊的事情")
a_func()
print("終于結束函式呼叫了,我都快累死了")
return wrapTheFunction
@a_new_decorator
def a_function_requiring_decoration():
print("我是一個需要裝飾的函式")
print(a_function_requiring_decoration.__name__)
a_function_requiring_decoration()
上述語法糖"@a_new_decorator"等價于 未重構之前的“a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)“
注意:
我們發現“a_function_requiring_decoration._name_”回傳的是wrapTheFunction,也就是說原函式在經歷裝飾器后函式的名字和函式的注釋、檔案都被修改成了裝飾器閉包內的函式
為了防止這種情況的出現
我們匯入一個模塊
import functools/from functools import wraps
import functools
def a_new_decorator(a_func):
@functools.wraps(a_func)
def wrapTheFunction():
print("在函式呼叫前我正在做一些無聊的事情")
a_func()
print("終于結束函式呼叫了,我都快累死了")
return wrapTheFunction
@a_new_decorator
def a_function_requiring_decoration():
print("我是一個需要裝飾的函式")
print(a_function_requiring_decoration.__name__)
a_function_requiring_decoration()
就可以解決這個問題了
也可以通過以下兩個方法:
- 使用decorator.py檔案
decorator.py 是一個非常簡單的裝飾器加強包,你可以很直觀的先定義包裝函式wrapper(),再使用decorate(func, wrapper)方法就可以完成一個裝飾器,
decorator.py實作的裝飾器能完整保留原函式的name,doc和args
唯一有問題的就是inspect.getsource(func)回傳的還是裝飾器的源代碼需要改成inspect.getsource(func._wrapped_)
import decorator
import decorator
import datetime
# 裝飾器的優化
def wrapper(func, *args, **kwargs):
print("我正在裝扮自己")
return func(*args, **kwargs)
def logging(func):
# 用wrapper裝飾func
return decorator.decorate(func, wrapper)
# @logging
def hi():
print("my name is Q")
a= logging(hi)
a()
- 使用 wrapt檔案
import wrapt
wrapt是一個功能非常完善的包,用于實作各種裝飾器
使用wrapt實作的裝飾器不需要擔心之前inspect中遇到的所有問題,因為它都幫你處理了,甚至inspect.getsource(func)也準確無誤
import wrapt
@wrapt.decorator
def logging(wrapped, instance, *args, **kwargs):
print("我是個裝飾器的外套")
return wrapped(*args, **kwargs)
@logging
def sayHi(*args, **kwargs):
print("Hi")
sayHi()
帶引數的裝飾器
1.基于函式實作的裝飾器
在裝飾器外再套一層裝飾器,專門用于向裝飾器內部傳遞引數
import functools
def add_2_somenumber(num, add_num=1):
print("---1---")
def know_whatToDo(func):
print("---2---")
@functools.wraps(func)
def wirte_function_name(*arg, **kwargs):
print("---3---")
print(func.__name__, " was called at here")
print("as a result, the answer is %d" % (num + add_num))
return func(*arg, **kwargs)
return wirte_function_name
return know_whatToDo
@add_2_somenumber(2,3)
def print_result():
print("開始活動了")
print("---4---")
print_result()
2.基于類實作的裝飾器
裝飾器函式其實是這樣一個介面約束
它必須接受一個callable物件作為引數,然后回傳一個callable物件
在Python中一般callable物件都是函式
但也有例外,只要某個物件多載了__call__()方法,那么這個物件就是callable的
在class物件中:
_init_:用來傳遞引數
_call_:用來構建裝飾器
# 裝飾類
import functools
class logit(object):
def __int__(self, logfile="out.log"):
self.login_file = logfile
def __call__(self, func):
@functools.wraps(func)
def wrapped_function(*arg, **kwarg):
login_string = func.__name__+" was called "
print(login_string)
return func(*arg, **kwarg)
return wrapped_function
@logit(logfile="out.log")
def myfunc_test():
print("這是類裝飾器的產生")
myfunc_test()
1)不能修改原函式
2)不能修改呼叫方式
2、裝飾器通過嵌套函式和閉包實作
3、裝飾器執行順序:洋蔥法則
4、裝飾器通過語法糖“@”修飾
5、謹記裝飾器回傳的是持有被裝飾函式參考的閉包函式的參考這條原則
常用的裝飾器
屬性有三個裝飾器:setter, getter, deleter ,都是在property()的基礎上做了一些封裝
因為setter和deleter是property()的第二和第三個引數,不能直接套用@語法
class Classmate:
def __init__(self):
self.age = 15
@property
def set_name(self, value):
self.name = value
student = Classmate()
student.name="Q"
print(student.age)
print(student.name)
有了@property裝飾器的了解,這兩個裝飾器的原理是差不多的
@staticmethod回傳的是一個staticmethod類物件
@classmethod回傳的是一個classmethod類物件
他們都是呼叫的是各自的__init__()建構式
迭代器
from collections.abc import Iterable
from collections.abc import Iterator
content = list()
content = [x*x for x in range(10)]
print(type(content))
可以發現 常見的串列、字典、集合、元祖、字串都屬于迭代物件
print(isinstance([], Iterable))
print(isinstance((), Iterable))
print(isinstance({}, Iterable))
print(isinstance("", Iterable))
迭代物件都可以通過for遍歷
for i in content:
print(i, end=" ")
print()
類能不能是迭代物件呢?
class ClassMate(object):
def __init__(self):
self.names = []
def add_name(self, name):
self.names.append(name)
student = ClassMate()
student.add_name("老王")
student.add_name("小張")
student.add_name("小李")
print(isinstance(student, Iterable))
發現普通的類不是可迭代物件
只用當當類物件中出現__iter__方法時,該類就變成了可迭代物件
class ClassMate(object):
def __init__(self):
self.names = []
def add_name(self, name):
self.names.append(name)
def __iter__(self):
pass
student = ClassMate()
student.add_name("老王")
student.add_name("小張")
student.add_name("小李")
# 當類物件中出現__iter__方法時,該類就變成了可迭代物件
print(isinstance(student, Iterable))
# 我們使用for回圈遍歷,發現還是不能夠迭代類物件
# 這時候我們就可以使用類中的一個方法__next__,使其迭代物件
try:
for i in student:
print(i)
except Exception as e:
print("不能夠進行迭代")
1. 通過一個可迭代的類來呼叫原本自身類的迭代
class ClassMate(object):
def __init__(self):
self.names = []
self.index = 0
def add_name(self, name):
self.names.append(name)
def __iter__(self):
# 回傳一個可以迭代的物件
return ClassRoom(self)
def __next__(self):
if self.index+1 <= len(self.names):
result = self.names[self.index]
self.index += 1
return result
else:
# 如果沒有這句話,物件將會一直回傳None
# 這里報錯StopIteration,并停止迭代
raise StopIteration
class ClassRoom(object):
def __init__(self, obj):
self.index = 0
self.obj = obj
def __iter__(self):
pass
def __next__(self):
if self.index + 1 <= len(self.obj.names):
result = self.obj.names[self.index]
self.index += 1
return result
else:
# 如果沒有這句話,物件將會一直回傳None
# 這里報錯StopIteration,并停止迭代
raise StopIteration
student = ClassMate()
student.add_name("老王")
student.add_name("小張")
student.add_name("小李")
for i in student:
print(i)
2. 自己迭代
class ClassMate(object):
def __init__(self):
self.names = []
self.index = 0
def add_name(self, name):
self.names.append(name)
def __iter__(self):
# 回傳一個可以迭代的物件
return self
def __next__(self):
if self.index+1 <= len(self.names):
result = self.names[self.index]
self.index += 1
return result
else:
# 如果沒有這句話,物件將會一直回傳None
# 這里報錯StopIteration,并停止迭代
raise StopIteration
student = ClassMate()
student.add_name("老王")
student.add_name("小張")
student.add_name("小李")
for i in student:
print(i)
生成器
生成器是一種特殊的迭代器
普通的生成器
只需要把迭代器生成時的中括號改成小括號
def get_test1(num):
print(num)
i = 0
print(i, end=" ")
while i < num:
print(i, end=" ")
ret = yield i
i += 1
n = get_test1(10)
for i in range(10):
next(n)
def get_test2(num):
print(num)
i = 0
print(i, end=" ")
while i < num:
print(i, end=" ")
ret = yield i
print(ret)
i += 1
n1 = get_test2(10)
next(n1)
n1.send("hahahaha")
next(n1)
當函式呼叫時出現了yield,它就變成了一個生成器
生成器可以通過_next_來獲取資料
obj.send(msg)當程式進行時,使yield呼叫擁有回傳值,其值為send傳輸過去的msg
注意:send方法呼叫時必須先呼叫next方法開始迭代生成
當子函式運行到yield時,程式會先將數值回傳個函式呼叫,然后停止等待,一直到下一次獲取生成器中資料時才啟動
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/190205.html
標籤:python
上一篇:Anaconda常用命令小結
