recursive_repr(fillvalue=’,’)
python装饰器的使用 其中recursive_repr装饰器的目的是防止递归,提供指定返回值fillvalue 在实例化Mylist为对象m后,再递归调用m.append(m),执行两次wrapper。原因是第一次执行wrapper后进入def __repr__后,有一个递归对象m,再执行wrapper。
from _thread import get_ident
def recursive_repr(fillvalue=',,,'):
'Decorator to make a repr function return fillvalue for a recursive call'
def decorating_function(user_function):
repr_running = set()
def wrapper(self):
key = id(self), get_ident()
print("key",key)
print("repr_running_1",repr_running)
if key in repr_running:
return fillvalue
repr_running.add(key)
try:
print("1111111111")
result = user_function(self)
print("-------")
finally:
repr_running.discard(key)
print("repr_running_2",repr_running)
print('//n')
return result
wrapper.__module__ = getattr(user_function, '__module__')
wrapper.__doc__ = getattr(user_function, '__doc__')
wrapper.__name__ = getattr(user_function, '__name__')
wrapper.__qualname__ = getattr(user_function, '__qualname__')
wrapper.__annotations__ = getattr(user_function, '__annotations__', {})
return wrapper
return decorating_function
class MyList(list):
@recursive_repr()
def __repr__(self):
return '<' + '|'.join(map(repr,self)) + '>'
m = MyList('sdsd')
print(m)
m.append('x')
print(m)
m.append(m) /*执行两次wrapper*/
print(m)
|