builtin_property.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. # test builtin property
  2. try:
  3. property
  4. except:
  5. print("SKIP")
  6. raise SystemExit
  7. # create a property object explicitly
  8. property()
  9. property(1, 2, 3)
  10. # use its accessor methods
  11. p = property()
  12. p.getter(1)
  13. p.setter(2)
  14. p.deleter(3)
  15. # basic use as a decorator
  16. class A:
  17. def __init__(self, x):
  18. self._x = x
  19. @property
  20. def x(self):
  21. print("x get")
  22. return self._x
  23. a = A(1)
  24. print(a.x)
  25. try:
  26. a.x = 2
  27. except AttributeError:
  28. print("AttributeError")
  29. # explicit use within a class
  30. class B:
  31. def __init__(self, x):
  32. self._x = x
  33. def xget(self):
  34. print("x get")
  35. return self._x
  36. def xset(self, value):
  37. print("x set")
  38. self._x = value
  39. def xdel(self):
  40. print("x del")
  41. x = property(xget, xset, xdel)
  42. b = B(3)
  43. print(b.x)
  44. b.x = 4
  45. print(b.x)
  46. del b.x
  47. # full use as a decorator
  48. class C:
  49. def __init__(self, x):
  50. self._x = x
  51. @property
  52. def x(self):
  53. print("x get")
  54. return self._x
  55. @x.setter
  56. def x(self, value):
  57. print("x set")
  58. self._x = value
  59. @x.deleter
  60. def x(self):
  61. print("x del")
  62. c = C(5)
  63. print(c.x)
  64. c.x = 6
  65. print(c.x)
  66. del c.x
  67. # a property that has no get, set or del
  68. class D:
  69. prop = property()
  70. d = D()
  71. try:
  72. d.prop
  73. except AttributeError:
  74. print('AttributeError')
  75. try:
  76. d.prop = 1
  77. except AttributeError:
  78. print('AttributeError')
  79. try:
  80. del d.prop
  81. except AttributeError:
  82. print('AttributeError')
  83. # properties take keyword arguments
  84. class E:
  85. p = property(lambda self: 42, doc="This is truth.")
  86. # not tested for because the other keyword arguments are not accepted
  87. # q = property(fget=lambda self: 21, doc="Half the truth.")
  88. print(E().p)
  89. # a property as an instance member should not be delegated to
  90. class F:
  91. def __init__(self):
  92. self.prop_member = property()
  93. print(type(F().prop_member))