1
0

420_decorator.py 997 B

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