Home > Article > Backend Development > Python learning agent mode
This article mainly introduces the implementation of proxy mode in Python. It uses an interesting example to write a demonstration code, which has certain reference value. Interested friends can learn about it. I hope it will be helpful to you.
Definition of proxy mode: Provide a proxy for other objects to control access to this object. In some cases, one object is not suitable or cannot directly reference another object, and a proxy object can act as an intermediary between the client and the target object.
Application scenarios of proxy mode:
1. Remote proxy, that is, providing local representation for an object in different address spaces. This hides the fact that an object exists in a different address space.
2. Virtual agents are expensive objects to create as needed. It is used to store real objects that take a long time to instantiate. For example, in HTML, pictures take a long time to load, so virtual agents are used to replace real pictures.
3. Security agent is used to control access to real objects. Permissions
4. Intelligent guidance means that when the real object is called, the agent handles other things
For example: Male A likes Female A, but he does not dare to confess to her. Therefore, male B is entrusted as an agent to send gifts to female A on his behalf. The key point in realizing this requirement is that male A and female A do not have direct contact with each other. They all achieve indirect contact through the agent male B.
#encoding=utf-8 __author__ = 'kevinlu1010@qq.com' from abc import ABCMeta, abstractmethod class FemaleA(): def __init__(self, name): self.name = name class Male(): __metaclass__ = ABCMeta @abstractmethod def send_flower(self): pass @abstractmethod def send_chocolate(self): pass @abstractmethod def send_book(self): pass class MaleA(Male): def __init__(self, name, love_female): self.name = name self.love_female = FemaleA(love_female) def send_flower(self): print '%s送花给%s' % (self.name, self.love_female.name) def send_chocolate(self): print '%s送巧克力给%s' % (self.name, self.love_female.name) def send_book(self): print '%s送书给%s' % (self.name, self.love_female.name) class Proxy(Male): def __init__(self, name, proxyed_name, love_female): self.name = name self.proxyed = MaleA(proxyed_name, love_female) def send_flower(self): self.proxyed.send_flower() def send_chocolate(self): self.proxyed.send_chocolate() def send_book(self): self.proxyed.send_book() if __name__ == '__main__': p = Proxy('男B', '男A', '女A') p.send_book() p.send_chocolate() p.send_flower()
Related tutorials: Python video tutorial
The above is the detailed content of Python learning agent mode. For more information, please follow other related articles on the PHP Chinese website!