I'm currently playing around with Design Patterns in Python. I tried to write a generic Proxy which counts calls to attributes/functions. This works fine with getattr for own types, but doesn't work for stuff like str(), len() etc. So I tried dynamically remapping the function calls to the functions of the child object, but It doesn't work. Anyone can help me out on this?
class CountAccessProxy():
def __init__(self, obj):
self._obj = obj
self.updateFuncs(dir(obj))
self.countAccess={}
print(self.__dict__)
def __getattr__(self, att):
self.countAccess[att]= self.countAccess.setdefault(att, 0) +1
return getattr(self._obj, att)
def updateFuncs(self,funcs):
for func in funcs:
if "__" in func:
#Try to remap the functions to the functions of child obj
self.__dict__[func] = getattr(self._obj,func)
listy = CountAccessProxy([0,2,5,5])
print(len(listy))
Traceback (most recent call last):
File "proxy.py", line 52, in <module>
print(len(listy))
TypeError: object of type 'CountAccessProxy' has no len()
Aucun commentaire:
Enregistrer un commentaire