The simple description of the task is that in the new Style object model, the Python operation is actually looking for a special method in the class (the classic object is manipulated in the instance), and now needs to wrap some new style instances into the proxy, which can choose to delegate some special methods to the inner wrapped object.
The code is implemented as:
1 classProxy (object):2 """base class for all agents"""3 def __init__(self, obj):4Super (Proxy, self).__init__()#this complement will result in infinite recursive loops5Self._obj =obj6 7 def __getattr__(self, attribute):8 returngetattr (Self._obj, attribute)9 Ten One defMake_binder (unbound_method): A defWrapper (self, *arg, * *Kwargs): - returnUnbound_method (Self._obj, *arg, * *Kwargs) - returnwrapper the - -Known_proxy_classes = {} - + - defProxy (obj, *specials): + """Factory Functions""" AObj_cls = obj.__class__ atKey =Obj_cls, Specials -CLS =known_proxy_classes.get (Key) - ifCls isNone: -CLS = Type ("%sproxy"% Ob_cls.__name, (Proxy,), {}) - forNameinchSpecials: -Name ='__%s__'%name inUnbound_method =getattr (OBJ_CLS, name) - SetAttr (CLS, name, Make_binder (Unbound_method)) to """caching for further use + Known_proxy_classes[key] = CLS - """instantiate and return the required proxy the returnCLS (obj)
Proxies (and auto-hosting) are all attributed to the __getattr__ mechanism, and Python automatically calls __getattr__ when querying any attribute (including methods, Python does not differentiate between them).
The result of the code operation is as follows:
In fact, the result is very easy to understand, is through a special method proxy implementation of the subclass method Proxy, such as the above example, because the agent of the list of Len and ITER, then the method can be implemented Len and iteration, there is no proxy Geiitem method, then the use of index will be an error.
In new Style objects, Python operations do not look for special methods at run time: they depend on the "slot" of the class object. These slots are updated when the object is created or modified, so for a proxy object, if it wants to host a special method to the encapsulated object, it must itself belong to a custom-made class.
Python code implementations that host special methods in proxies