null.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """http://code.activestate.com/recipes/68205-null-object-design-pattern/"""
  4. class Null:
  5. def __init__(self, *args, **kwargs):
  6. """Ignore parameters."""
  7. return None
  8. def __call__(self, *args, **kwargs):
  9. """Ignore method calls."""
  10. return self
  11. def __getattr__(self, mname):
  12. """Ignore attribute requests."""
  13. return self
  14. def __setattr__(self, name, value):
  15. """Ignore attribute setting."""
  16. return self
  17. def __delattr__(self, name):
  18. """Ignore deleting attributes."""
  19. return self
  20. def __repr__(self):
  21. """Return a string representation."""
  22. return "<Null>"
  23. def __str__(self):
  24. """Convert to a string and return it."""
  25. return "Null"
  26. def test():
  27. """
  28. Perform some decent tests, or rather: demos.
  29. >>> print(Null())
  30. Null
  31. >>> print(Null('value'))
  32. Null
  33. >>> n= Null('vale',param='value')
  34. >>> print(n)
  35. Null
  36. >>> n()
  37. <Null>
  38. >>> n('value')
  39. <Null>
  40. >>> n('value', param='value')
  41. <Null>
  42. >>> print(n)
  43. Null
  44. """
  45. # constructing and calling
  46. #n = Null()
  47. #print(n)
  48. #n = Null('value')
  49. #print(n)
  50. n = Null('value', param='value')
  51. #print(n)
  52. n()
  53. #n('value')
  54. #n('value', param='value')
  55. #print(n)
  56. # attribute handling
  57. n.attr1
  58. print('attr1', n.attr1)
  59. n.attr1.attr2
  60. n.method1()
  61. n.method1().method2()
  62. n.method('value')
  63. n.method(param='value')
  64. n.method('value', param='value')
  65. n.attr1.method1()
  66. n.method1().attr1
  67. n.attr1 = 'value'
  68. n.attr1.attr2 = 'value'
  69. del n.attr1
  70. del n.attr1.attr2.attr3
  71. # representation and conversion to a string
  72. assert repr(n) == '<Null>'
  73. assert str(n) == 'Null'
  74. if __name__ == '__main__':
  75. test()
  76. import doctest
  77. doctest.testmod()
  78. ### OUTPUT ###
  79. # Null
  80. # Null
  81. # Null
  82. # Null
  83. # attr1 Null