44_decorator.py 939 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. from functools import cache
  2. class A:
  3. def __init__(self, x):
  4. self._x = x
  5. @property
  6. def x(self):
  7. return self._x
  8. a = A(1)
  9. assert a.x == 1
  10. class B:
  11. def __init__(self):
  12. self._x = 1
  13. def _x_setter(self, v):
  14. self._x = v
  15. B.x = property(
  16. lambda self: self._x,
  17. B._x_setter
  18. )
  19. b = B()
  20. assert b.x == 1
  21. b.x = 2
  22. assert b.x == 2
  23. @cache
  24. @cache
  25. @cache
  26. def fib(n):
  27. # print(f'fib({n})')
  28. if n < 2:
  29. return n
  30. return fib(n-1) + fib(n-2)
  31. assert fib(32) == 2178309
  32. def wrapped(cls):
  33. return int
  34. @wrapped
  35. @wrapped
  36. @wrapped
  37. @wrapped
  38. class A:
  39. def __init__(self) -> None:
  40. pass
  41. assert A('123') == 123
  42. # validate the decorator order
  43. res = []
  44. def w(x):
  45. res.append('w')
  46. return x
  47. def w1(x):
  48. res.append('w1')
  49. return x
  50. def w2(x):
  51. res.append('w2')
  52. return x
  53. @w
  54. @w1
  55. @w2
  56. def f():
  57. pass
  58. f()
  59. assert res == ['w2', 'w1', 'w']