python裝飾器property和setter用法
1.引子:函數(shù)也是對(duì)象
木有括號(hào)的函數(shù)那就不是在調(diào)用。
def hi(name="yasoob"):
return "hi " + name
print(hi())
# output: 'hi yasoob'
# 我們甚至可以將一個(gè)函數(shù)賦值給一個(gè)變量,比如
greet = hi
# 我們這里沒有在使用小括號(hào),因?yàn)槲覀儾⒉皇窃谡{(diào)用hi函數(shù)
# 而是在將它放在greet變量里頭。我們嘗試運(yùn)行下這個(gè)
print(greet())
# output: 'hi yasoob'
# 如果我們刪掉舊的hi函數(shù),看看會(huì)發(fā)生什么!
del hi
print(hi())
#outputs: NameError
print(greet())
#outputs: 'hi yasoob'2.函數(shù)內(nèi)的函數(shù)
(1)在python中,一個(gè)函數(shù)內(nèi)能嵌套定義另一個(gè)函數(shù),并且可以在該大函數(shù)內(nèi)調(diào)用該小函數(shù)。
def hi(name="yasoob"):
print("now you are inside the hi() function")
def greet():
return "now you are in the greet() function"
def welcome():
return "now you are in the welcome() function"
print(greet())
print(welcome())
print("now you are back in the hi() function")
hi()
#output:now you are inside the hi() function
# now you are in the greet() function
# now you are in the welcome() function
# now you are back in the hi() function
# 上面展示了無論何時(shí)你調(diào)用hi(), greet()和welcome()將會(huì)同時(shí)被調(diào)用。
# 然后greet()和welcome()函數(shù)在hi()函數(shù)之外是不能訪問的,比如:
greet()
#outputs: NameError: name 'greet' is not defined(2)開始神奇的是,大函數(shù)的返回值可以是一個(gè)函數(shù):
def hi(name="yasoob"): def greet(): return "now you are in the greet() function" def welcome(): return "now you are in the welcome() function" if name == "yasoob": return greet #這里??! else: return welcome a = hi() print(a) #outputs: <function greet at 0x7f2143c01500> #上面清晰地展示了`a`現(xiàn)在指向到hi()函數(shù)中的greet()函數(shù) #現(xiàn)在試試這個(gè) print(a()) #outputs: now you are in the greet() function
在 if/else 語句中我們返回 greet 和 welcome,而不是 greet() 和 welcome()。
為什么那樣?這是因?yàn)楫?dāng)你把一對(duì)小括號(hào)放在后面,這個(gè)函數(shù)就會(huì)執(zhí)行;然而如果你不放括號(hào)在它后面,那它可以被到處傳遞,并且可以賦值給別的變量而不去執(zhí)行它。
當(dāng)我們寫下 a = hi(),hi() 會(huì)被執(zhí)行,而由于 name 參數(shù)默認(rèn)是 yasoob,所以函數(shù) greet 被返回了。
PS:如果我們打印出 hi()(),這會(huì)輸出 now you are in the greet() function。
(3)最后要說的是函數(shù)作為參數(shù)傳入一個(gè)函數(shù):
def hi():
return "hi yasoob!"
def doSomethingBeforeHi(func):
print("I am doing some boring work before executing hi()")
print(func())
doSomethingBeforeHi(hi)
#outputs:I am doing some boring work before executing hi()
# hi yasoob!3.裝飾器小栗子
終于來到了帶@的裝飾器,其實(shí)就是帶了@帽子的函數(shù)作為參數(shù),傳入@后面的函數(shù)中。
def a_new_decorator(a_func):
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
@a_new_decorator
def a_function_requiring_decoration():
"""Hey you! Decorate me!"""
print("I am the function which needs some decoration to "
"remove my foul smell")
a_function_requiring_decoration()
#outputs: I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()
#the @a_new_decorator is just a short way of saying:
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)上面的代碼等價(jià)于我們熟悉的:
def a_new_decorator(a_func):
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
def a_function_requiring_decoration():
print("I am the function which needs some decoration to remove my foul smell")
a_function_requiring_decoration()
#outputs: "I am the function which needs some decoration to remove my foul smell"
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
#now a_function_requiring_decoration is wrapped by wrapTheFunction()
a_function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()不過一開始上面被裝飾過的函數(shù)名字已經(jīng)悄悄發(fā)生“改變”,如果print下可以看出(如下代碼)。
解決方案:
@wraps接受一個(gè)函數(shù)來進(jìn)行裝飾,并加入了復(fù)制函數(shù)名稱、注釋文檔、參數(shù)列表等等的功能。這可以讓我們?cè)谘b飾器里面訪問在裝飾之前的函數(shù)的屬性。
print(a_function_requiring_decoration.__name__) # Output: wrapTheFunction
最終加上@wraps的代碼如下:
from functools import wraps
def a_new_decorator(a_func):
@wraps(a_func)
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
@a_new_decorator
def a_function_requiring_decoration():
"""Hey yo! Decorate me!"""
print("I am the function which needs some decoration to "
"remove my foul smell")
print(a_function_requiring_decoration.__name__)
# Output: a_function_requiring_decoration5.property和setter用法
class Timer:
def __init__(self, value = 0.0):
self._time = value
self._unit = 's'
# 使用裝飾器的時(shí)候,需要注意:
# 1. 裝飾器名,函數(shù)名需要一直
# 2. property需要先聲明,再寫setter,順序不能倒過來
@property
def time(self):
return str(self._time) + ' ' + self._unit
@time.setter
def time(self, value):
if(value < 0):
raise ValueError('Time cannot be negetive.')
self._time = value
t = Timer()
t.time = 1.0
print(t.time)到此這篇關(guān)于python裝飾器property和setter用法的文章就介紹到這了,更多相關(guān)python property與setter內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python利用pdfplumber庫提取pdf中表格數(shù)據(jù)
pdfplumber是一個(gè)用于從PDF文檔中提取文本和表格數(shù)據(jù)的Python庫,它可以幫助用戶輕松地從PDF文件中提取有用的信息,例如表格、文本、元數(shù)據(jù)等,本文介紹了如何通過Python的pdfplumber庫提取pdf中表格數(shù)據(jù),感興趣的同學(xué)可以參考一下2023-05-05
python關(guān)于矩陣重復(fù)賦值覆蓋問題的解決方法
這篇文章主要介紹了python關(guān)于矩陣重復(fù)賦值覆蓋問題的解決方法,涉及Python深拷貝與淺拷貝相關(guān)操作與使用技巧,需要的朋友可以參考下2019-07-07
對(duì)Python實(shí)現(xiàn)累加函數(shù)的方法詳解
今天小編就為大家分享一篇對(duì)Python實(shí)現(xiàn)累加函數(shù)的方法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01
python實(shí)現(xiàn)統(tǒng)計(jì)代碼行數(shù)的小工具
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)統(tǒng)計(jì)代碼行數(shù)的小工具,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-09-09
python使用selenium登錄QQ郵箱(附帶滑動(dòng)解鎖)
這篇文章主要為大家詳細(xì)介紹了python使用selenium登錄QQ郵箱,帶滑動(dòng)解鎖登錄功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01
Python實(shí)現(xiàn)實(shí)時(shí)顯示進(jìn)度條的六種方法
這篇文章主要為大家介紹了Python實(shí)現(xiàn)實(shí)時(shí)顯示進(jìn)度條,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助<BR>2021-12-12
Python3.7.0 Shell添加清屏快捷鍵的實(shí)現(xiàn)示例
這篇文章主要介紹了Python3.7.0 Shell添加清屏快捷鍵的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
如何打包Python Web項(xiàng)目實(shí)現(xiàn)免安裝一鍵啟動(dòng)的方法
這篇文章主要介紹了如何打包Python Web項(xiàng)目,實(shí)現(xiàn)免安裝一鍵啟動(dòng),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-05-05
Python通過matplotlib畫雙層餅圖及環(huán)形圖簡單示例
這篇文章主要介紹了Python通過matplotlib畫雙層餅圖及環(huán)形圖簡單示例,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12

