日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

Python 代理类实现和控制访问与修改属性的权限

發(fā)布時間:2024/7/5 python 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python 代理类实现和控制访问与修改属性的权限 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

本篇文章主要內(nèi)容

代理類主要功能是將一個類實例的屬性訪問和控制代理到代碼內(nèi)部另外一個實例類,將想對外公布的屬性的訪問和控制權(quán)交給代理類來操作,保留不想對外公布的屬性的訪問或控制權(quán),比如只讀訪問,日志功能

  • 在代理類中實現(xiàn)被代理的類屬性訪問和修改權(quán)限控制
  • 異常捕獲代理類的簡化示例
  • 代理類的一個簡單的實現(xiàn)方式示例

    目標:實現(xiàn)類Product的實例屬性讓另一個類Proxy來代理訪問和控制,想將對外公布的屬性交給代理類讓外部訪問和控制,不想對外公布的屬性無法通過代理來訪問和控制,這里不想對外公布的屬性約定用下劃線命名開頭

    # proxy_example1.py # 以下是一個代理類實現(xiàn)只讀訪問的示例 # 目標:代理后只能訪問和修改Product的公開屬性,私有屬性_current只能查看不能修改 class Product:def __init__(self, price, quantity):self.price = priceself.quantity = quantityself._current = 123# 只暴露代理類Proxy給外部使用 class Proxy:def __init__(self, obj):self._obj = objdef __getattr__(self, item): # 本實例沒有找到的屬性會執(zhí)行__getattr__方法if item.startswith("_"): # 約定下劃線開頭的方法不能訪問到被代理的類,只會訪問到代理類raise Exception(f"{item} not found") # Product存在的私有屬性也不希望被外部知道return getattr(self._obj, item)def __setattr__(self, key, value):if key.startswith("_"): # 約定下劃線開頭的方法不能訪問到被代理的類,只會訪問到代理類# 注:這里不能raise,這會導(dǎo)致Proxy的實例都無法創(chuàng)建(__dict__等屬性無法創(chuàng)建)super(Proxy, self).__setattr__(key, value) # 避免無限循環(huán)else:setattr(self._obj, key, value)# 要求只能刪除非下劃線開頭的屬性def __delattr__(self, item):if item.startswith("_"):super(Proxy, self).__delattr__(item) # 避免無限循環(huán)else:delattr(self._obj, item)def test_getattr():p = Product(10, 1)pp = Proxy(p)print(pp.price)print(pp._curr)def test_setattr():p = Product(10, 2)pp = Proxy(p)pp.abc = 1print(pp.abc, p.abc)pp._curr = 10000print(pp._curr) # 私有屬性,設(shè)置給了代理類print(p._curr) # raise an error, 被代理的類Product的屬性沒有設(shè)置成功也無法訪問def test_delattr():p = Product(10, 2)pp = Proxy(p)pp.abc = 123print(pp.abc, p.abc)# 刪除公開屬性del pp.abc # 成功# print(pp.abc, p.abc) # 已被刪除# # 刪除私有屬性# del pp._curr # 會嘗試刪除Proxy的私有屬性,raise AttributeError: _curr# 先創(chuàng)建在刪除pp._def = 123 # 這個操作只會設(shè)置Proxy的實例屬性print(pp._def) # 訪問的是Proxy實例屬性,被代理的Product實例沒有創(chuàng)建_def屬性# del pp._def # 刪除的是Proxy的實例屬性# print(pp._def)

    測試獲取屬性

    if __name__ == '__main__':test_getattr()

    輸出:

    10 ... Exception: _curr not found ...

    測試設(shè)置屬性

    if __name__ == '__main__':test_setattr()

    輸出

    1 1 10000 ... AttributeError: 'Product' object has no attribute '_curr' ...

    測試刪除屬性

    if __name__ == '__main__':test_delattr()

    輸出

    123 123 123

    注:以雙下劃線開頭和結(jié)尾的方法無法被代理,想要使用,必須在代理類中定義出這個方法,然后重定向到被代理的類的方法,比如你想使用isinstance()方法就要在Proxy偽造定義__class__屬性,想要使用len()方法就要在Proxy定義__len__方法

    # proxy_example2.py class Product:def __init__(self, price, quantity):self.price = priceself.quantity = quantityself._current = 123def __len__(self):return 111# 只暴露代理類Proxy給外部使用 class Proxy:def __init__(self, obj):self._obj = objdef __getattr__(self, item): # 本實例沒有找到的屬性會執(zhí)行__getattr__方法if item.startswith("_"): # 約定下劃線開頭的方法不能訪問到被代理的類,只會訪問到代理類raise Exception(f"{item} not found") # Product存在的私有屬性也不希望被外部知道return getattr(self._obj, item)def __setattr__(self, key, value):if key.startswith("_"): # 約定下劃線開頭的方法不能訪問到被代理的類,只會訪問到代理類# 注:這里不能raise,這會導(dǎo)致Proxy的實例都無法創(chuàng)建(__dict__等屬性無法創(chuàng)建)super(Proxy, self).__setattr__(key, value) # 避免無限循環(huán)else:setattr(self._obj, key, value)# 要求只能刪除非下劃線開頭的屬性def __delattr__(self, item):if item.startswith("_"):super(Proxy, self).__delattr__(item) # 避免無限循環(huán)else:delattr(self._obj, item)@propertydef __class__(self): # 偽造__class__屬性return self._obj.__class__def __len__(self):return len(self._obj)def test_instance():p = Product(10, 2)pp = Proxy(p)print(pp.__class__)print(isinstance(pp, Product)) # 如果不偽造__class__,會返回Falsedef test_len():p = Product(10, 2)pp = Proxy(p)print(len(pp)) # 如果Proxy實例不定義__len__方法,會報錯TypeError: object of type 'Proxy' has no len()

    測試偽造的實例class類型

    if __name__ == '__main__':test_instance()

    輸出

    <class '__main__.Product'> True

    測試獲取長度

    if __name__ == '__main__':test_len()

    輸出

    111

    一個實現(xiàn)日志輸出的代理類的簡化示例

    捕獲web server報錯日志并執(zhí)行異常處理的示例

    # logger_proxy.py # -*- coding:utf-8 -*- from functools import wrapsclass DAL:@classmethoddef dm1(cls, req, *args):print("dm1...", f"{req=}")print(1/0) # 故意拋出異常return "dm1"class BLL:@classmethoddef bm1(cls, req):print("bm1...", f"{req=}")return DAL.dm1(req)class Application:def __init__(self, req):self.req = reqself._p = "private attr"def hd1(self):return BLL.bm1(self.req)class LoggerProxy:def __init__(self, obj):self._obj = objdef __getattr__(self, item): # LoggerProxy類實例沒獲取到的屬性會執(zhí)行這個方法attr = getattr(self._obj, item)if callable(attr): # 獲取到了方法,則處理異常捕獲@wraps(attr)def wrapped_method(*args, **kwargs):# print(f"Before accessing to attribute/method: {item}")try:method = attr(*args, **kwargs)except ZeroDivisionError:# 捕獲異常然后處理...raise Exception(f"{attr.__name__} received a zero division error.")# print(f"After attribute/method {item} returned")return methodreturn wrapped_methodelse: # 獲取到了屬性,直接返回return attrif __name__ == '__main__':lp = LoggerProxy(Application("abc"))print(lp.req)print(lp._p)print(lp.hd1())

    運行輸出

    abc private attr bm1... req='abc' dm1... req='abc' Traceback... ZeroDivisionError: division by zero During handling of the above exception, another exception occurred: Traceback... Exception: hd1 received a zero division error.

    總結(jié)

    本節(jié)主要的內(nèi)容是實現(xiàn)了一個代理類,達到代理訪問和控制某個類的屬性并避免將私有屬性暴露給外部,需要注意一些特殊方法,也就是python雙下劃線開頭和結(jié)尾的方法,如果想要被代理類訪問和控制就必須在代理類中也定義對應(yīng)的實際方法,另外,示例中主要是以下劃線開頭的方法作為私有屬性的約定,也可以使用其他約定,這樣在代理方法中的訪問和修改時做出相應(yīng)的判斷即可

    總結(jié)

    以上是生活随笔為你收集整理的Python 代理类实现和控制访问与修改属性的权限的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。