python3 property裝飾器實現(xiàn)原理與用法示例
本文實例講述了python3 property裝飾器實現(xiàn)原理與用法。分享給大家供大家參考,具體如下:
學習python的同學,慢慢的都會接觸到裝飾器,裝飾器在python里是功能強大的語法。裝飾器配合python的魔法方法,能實現(xiàn)很多意想不到的功能。廢話不多說,如果你已經(jīng)掌握了閉包的原理,代碼的邏輯還是可以看明白的,咱們直接進入正題。
property的意義
@property把一個類的getter方法變成屬性,如果還有setter方法,就在setter方法前面加上@method.setter。使用類屬性=property(getx,setx,delx,desc)也是可以的。
實現(xiàn)很簡單,那么它背后的原理是什么呢?
Property類的偽代碼如下,里面涉及了__get__、__set__、__delete__魔法方法。Decorator類是裝飾器類,Target是目標類。當你設置裝飾器類的實例對象為目標類的x屬性后,當試圖訪問目標類的x屬性會觸發(fā)裝飾器類的__get__方法;當為目標類的x屬性賦值時,會觸發(fā)裝飾器類的__setter__方法;嘗試刪除目標類的x屬性時,會觸發(fā)裝飾器類的__delete__方法。當訪問Target.x.__doc__,可以打印出裝飾器類的描述文檔。事實上這種裝飾器類也被稱為描述符類。描述符類就是將一個特殊類的實例指派給一個類的屬性。
類屬性實現(xiàn)方式:
class Decorator(object):
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
self.__doc__ = doc
def __get__(self, instance, owner):
if instance is None:
return self
return self.fget(instance)
def __set__(self, instance, value):
self.fset(instance, value)
def __delete__(self, instance):
self.fdel(instance)
def getter(self, fget):
return Decorator(fget, self.fset, self.fdel, self.__doc__)
def setter(self, fset):
return Decorator(self.fget, fset, self.fdel, self.__doc__)
def deleter(self, fdel):
return Decorator(self.fget, self.fset, fdel, self.__doc__)
class Target(object):
desc = "Amazing pyhton"
def __init__(self, attr=5):
self._x = attr
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = Decorator(getx,setx,delx,desc)
裝飾器實現(xiàn)方式:
class Decorator(object):
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
self.__doc__ = doc
def __get__(self, instance, owner):
if instance is None:
return self
return self.fget(instance)
def __set__(self, instance, value):
self.fset(instance, value)
def __delete__(self, instance):
self.fdel(instance)
def getter(self, fget):
return Decorator(fget, self.fset, self.fdel, self.__doc__)
def setter(self, fset):
return Decorator(self.fget, fset, self.fdel, self.__doc__)
def deleter(self, fdel):
return Decorator(self.fget, self.fset, fdel, self.__doc__)
class Target(object):
desc = "Amazing pyhton"
def __init__(self, attr=5):
self._x = attr
@Decorator
def show(self):
return self._x
@show.setter
def show(self, value):
self._x = value
@show.deleter
def show(self):
del self._x
更多關于Python相關內(nèi)容可查看本站專題:《Python數(shù)據(jù)結構與算法教程》、《Python Socket編程技巧總結》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python基類函數(shù)的重載與調(diào)用實例分析
這篇文章主要介紹了Python基類函數(shù)的重載與調(diào)用方法,實例分析了Python中基類函數(shù)的重載及調(diào)用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-01-01
Seaborn數(shù)據(jù)分析NBA球員信息數(shù)據(jù)集
這篇文章主要為大家介紹了Seaborn數(shù)據(jù)分析處理NBA球員信息數(shù)據(jù)集案例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09
python執(zhí)行js腳本報錯CryptoJS is not defined問題
這篇文章主要介紹了python執(zhí)行js腳本報錯CryptoJS is not defined問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05

