網站首頁 編程語言 正文
本篇文章主要內容
代理類主要功能是將一個類實例的屬性訪問和控制代理到代碼內部另外一個實例類,將想對外公布的屬性的訪問和控制權交給代理類來操作,保留不想對外公布的屬性的訪問或控制權,比如只讀訪問,日志功能
1.代理類實現被代理類的屬性訪問和修改權限控制
2.異常捕獲代理類的簡化示例
代理類的一個簡單的實現方式示例
目標:實現類Product
的實例屬性讓另一個類Proxy
來代理訪問和控制,想將對外公布的屬性交給代理類讓外部訪問和控制,不想對外公布的屬性無法通過代理來訪問和控制,這里不想對外公布的屬性約定用下劃線命名開頭
# proxy_example1.py # 以下是一個代理類實現只讀訪問的示例 # 目標:代理后只能訪問和修改Product的公開屬性,私有屬性_current只能查看不能修改 class Product: def __init__(self, price, quantity): self.price = price self.quantity = quantity self._current = 123 # 只暴露代理類Proxy給外部使用 class Proxy: def __init__(self, obj): self._obj = obj def __getattr__(self, item): # 本實例沒有找到的屬性會執行__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,這會導致Proxy的實例都無法創建(__dict__等屬性無法創建) super(Proxy, self).__setattr__(key, value) # 避免無限循環 else: setattr(self._obj, key, value) # 要求只能刪除非下劃線開頭的屬性 def __delattr__(self, item): if item.startswith("_"): super(Proxy, self).__delattr__(item) # 避免無限循環 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 = 1 print(pp.abc, p.abc) pp._curr = 10000 print(pp._curr) # 私有屬性,設置給了代理類 print(p._curr) # raise an error, 被代理的類Product的屬性沒有設置成功也無法訪問 def test_delattr(): p = Product(10, 2) pp = Proxy(p) pp.abc = 123 print(pp.abc, p.abc) # 刪除公開屬性 del pp.abc # 成功 # print(pp.abc, p.abc) # 已被刪除 # # 刪除私有屬性 # del pp._curr # 會嘗試刪除Proxy的私有屬性,raise AttributeError: _curr # 先創建在刪除 pp._def = 123 # 這個操作只會設置Proxy的實例屬性 print(pp._def) # 訪問的是Proxy實例屬性,被代理的Product實例沒有創建_def屬性 # del pp._def # 刪除的是Proxy的實例屬性 # print(pp._def)
測試獲取屬性
if __name__ == '__main__': test_getattr()
輸出:
10
...
Exception: _curr not found
...
測試設置屬性
if __name__ == '__main__': test_delattr()
輸出
1 1
10000
...
AttributeError: 'Product' object has no attribute '_curr'
...
測試刪除屬性
if __name__ == '__main__': test_delattr()
輸出
123 123
123
注:以雙下劃線開頭和結尾的方法無法被代理,想要使用,必須在代理類中定義出這個方法,然后重定向到被代理的類的方法,比如你想使用isinstance()
方法就要在Proxy
偽造定義__class__
屬性,想要使用len()
方法就要在Proxy
重定向返回到被代理的類的len方法
# proxy_example2.py class Product: def __init__(self, price, quantity): self.price = price self.quantity = quantity self._current = 123 def __len__(self): return 111 # 只暴露代理類Proxy給外部使用 class Proxy: def __init__(self, obj): self._obj = obj def __getattr__(self, item): # 本實例沒有找到的屬性會執行__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,這會導致Proxy的實例都無法創建(__dict__等屬性無法創建) super(Proxy, self).__setattr__(key, value) # 避免無限循環 else: setattr(self._obj, key, value) # 要求只能刪除非下劃線開頭的屬性 def __delattr__(self, item): if item.startswith("_"): super(Proxy, self).__delattr__(item) # 避免無限循環 else: delattr(self._obj, item) @property def __class__(self): # 偽造類 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__,會返回False def 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()
輸出
True
測試獲取長度
if __name__ == '__main__': test_len()
輸出
111
一個實現日志輸出的代理類的簡化示例
捕獲web server報錯日志并執行異常處理的示例
# logger_proxy.py # -*- coding:utf-8 -*- from functools import wraps class DAL: @classmethod def dm1(cls, req, *args): print("dm1...", f"{req=}") print(1/0) # 故意拋出異常 return "dm1" class BLL: @classmethod def bm1(cls, req): print("bm1...", f"{req=}") return DAL.dm1(req) class Application: def __init__(self, req): self.req = req self._p = "private attr" def hd1(self): return BLL.bm1(self.req) class LoggerProxy: def __init__(self, obj): self._obj = obj def __getattr__(self, item): # LoggerProxy類實例沒獲取到的屬性會執行這個方法 attr = getattr(self._obj, item) if callable(attr): # 獲取到了方法,則處理異常捕獲 @wraps(attr) def wrapped_method(*args, **kwargs): # print(f"Before access 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 method return wrapped_method else: # 獲取到了屬性,直接返回 return attr if __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.
總結
本節主要的內容是實現了一個代理類,達到代理訪問和控制某個類的屬性并避免將私有屬性暴露給外部,需要注意的是,一些特殊方法,也就是python雙下劃線開頭和結尾的方法,如果想要被代理類訪問和控制,就必須在代理類中也定義對應的實際方法,另外,示例中主要是以下劃線開頭的方法作為私有屬性的約定,也可以使用其他約定,這樣在代理方法中的訪問和修改時做出相應的判斷即可
原文鏈接:https://blog.csdn.net/Moelimoe/article/details/123609039
相關推薦
- 2022-09-27 詳解Django中CSRF和CORS的區別_python
- 2022-04-18 Python?變量類型實例詳解_python
- 2022-07-08 Python中號稱神仙的六個內置函數詳解_python
- 2022-12-26 C語言實現十六進制轉換為十進制的方法詳解_C 語言
- 2022-05-22 Nginx服務安裝及軟件升級_nginx
- 2023-01-09 基于Python實現拉格朗日插值法_python
- 2022-02-28 gyp info it worked if it ends with ok npm ERR 解決辦法
- 2022-08-27 DOS編寫腳本常用命令整理小結_DOS/BAT
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支