In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
The knowledge of this article "how to achieve the proxy class of Python" is not quite understood by most people, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to achieve the proxy class of Python" article.
An example of a simple implementation of a proxy class
Goal: to implement the instance properties of class Product to allow another class Proxy to proxy access and control. You want to give the published attributes to the proxy class for external access and control. Attributes that do not want to be exposed cannot be accessed and controlled through the agent. Here, the attribute conventions that do not want to be published start with an underscore.
# proxy_example1.py# the following is an example of a proxy class that implements read-only access # goal: only public properties of Product can be accessed and modified after a proxy Private attribute _ current can only be viewed and cannot be modified class Product: def _ _ init__ (self, price, quantity): self.price = price self.quantity = quantity self._current = 12 only expose proxy class Proxy for external use class Proxy: def _ init__ (self, obj): self._obj = obj def _ getattr__ (self Item): # attributes not found in this instance will execute the _ _ getattr__ method if item.startswith ("_"): # it is stipulated that the method at the beginning of the underscore cannot access the proxied class Only access to the private properties of the proxy class raise Exception (f "{item} not found") # Product and do not want to be known to the outside world return getattr (self._obj, item) def _ setattr__ (self, key, value): if key.startswith ("_"): # it is stipulated that the method at the beginning of the underscore cannot access the proxied class Only the proxy class will be accessed # Note: raise is not allowed here This will cause instances of Proxy not to be created (attributes such as _ _ dict__ cannot be created) super (Proxy, self). _ _ setattr__ (key, value) # avoid infinite loops else: setattr (self._obj, key, value) # requires that only attributes def _ _ delattr__ (self) that are not beginning with an underscore can be deleted Item): if item.startswith ("_"): super (Proxy, self). _ _ delattr__ (item) # avoid infinite loops 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) # Private attribute Set to proxy class print (p._curr) # raise an error, def test_delattr (): P = Product (10,2) pp = Proxy (p) pp.abc = 123 print (pp.abc, p.abc) # Delete public attribute del pp.abc # successful # print (pp.abc) P.abc) # has been deleted # # Delete the private attribute # del pp._curr # will try to delete the private attribute of Proxy Raise AttributeError: _ curr # first create the instance property print (pp._def) of Proxy after deleting pp._def = 123#. The proxied Product instance does not create _ def property # del pp._def # deletes the instance property of Proxy # print (pp._def)
Test get properties
If _ _ name__ = ='_ _ main__': test_getattr ()
Output:
ten
...
Exception: _ curr not found
...
Test Settings Properties
If _ _ name__ = ='_ _ main__': test_delattr ()
Output
1 1
10000
...
AttributeError: 'Product' object has no attribute' _ curr'
...
Test delete properties
If _ _ name__ = ='_ _ main__': test_delattr ()
Output
123 123
one hundred and twenty three
Note: a method that begins and ends with a double underscore cannot be proxied. If you want to use it, you must define this method in the proxy class, and then redirect it to the method of the proxied class. For example, if you want to use the isinstance () method, you have to forge the definition of _ _ class__ attribute in Proxy, and if you want to use the len () method, you have to redirect to the len method of the proxied class in Proxy.
# proxy_example2.pyclass Product: def _ init__ (self, price, quantity): self.price = price self.quantity = quantity self._current = 123def _ len__ (self): return 11 expose only proxy Proxy for external use class Proxy: def _ init__ (self, obj): self._obj = obj def _ getattr__ (self) Item): # attributes not found in this instance will execute the _ _ getattr__ method if item.startswith ("_"): # it is stipulated that the method at the beginning of the underscore cannot access the proxied class Only access to the private properties of the proxy class raise Exception (f "{item} not found") # Product and do not want to be known to the outside world return getattr (self._obj, item) def _ setattr__ (self, key, value): if key.startswith ("_"): # it is stipulated that the method at the beginning of the underscore cannot access the proxied class Only the proxy class will be accessed # Note: raise is not allowed here This will cause instances of Proxy not to be created (attributes such as _ _ dict__ cannot be created) super (Proxy, self). _ _ setattr__ (key, value) # avoid infinite loops else: setattr (self._obj, key, value) # requires that only attributes def _ _ delattr__ (self) that are not beginning with an underscore can be deleted Item): if item.startswith ("_"): super (Proxy, self). _ _ delattr__ (item) # avoid infinite loops else: delattr (self._obj Item) @ property def _ class__ (self): # forgery 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)) # if you don't forge _ _ class__ Return False def test_len (): P = Product (10,2) pp = Proxy (p) print (len (pp)) # if the Proxy instance does not define a _ _ len__ method, it will report an error TypeError: object of type 'Proxy' has no len ()
Test forged instance class type
If _ _ name__ = ='_ _ main__': test_instance ()
Output
True
Test acquisition length
If _ _ name__ = ='_ _ main__': test_len ()
Output
one hundred and eleven
A simplified example of a proxy class that implements log output
An example of capturing web server error logs and performing exception handling
# logger_proxy.py#-*-coding:utf-8-*-from functools import wrapsclass DAL: @ classmethod def dm1 (cls, req, * args): print ("dm1...", f "{req=}") print (1 req= 0) # deliberately throws an exception 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): # attributes not obtained by the instance of the LoggerProxy class will execute this method attr = getattr (self._obj, item) if callable (attr): # get the method Handle exception catch @ wraps (attr) def wrapped_method (* args, * * kwargs): # print (f "Before access to attribute/method: {item}") try: method = attr (* args, * * kwargs) except ZeroDivisionError: # catch exception and then handle. Raise Exception (f "{attr.__name__} received a zero division error.") # print (f "After attribute/method {item} returned") return method return wrapped_method else: # got the attribute Directly return return attrif _ _ name__ = ='_ main__': lp = LoggerProxy (Application ("abc")) print (lp.req) print (lp._p) print (lp.hd1 ())
Running output
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.
The above is about the content of this article on "how to realize the proxy class of Python". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.