null.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. """Perform some decent tests, or rather: demos."""
  28. # constructing and calling
  29. n = Null()
  30. print(n)
  31. n = Null('value')
  32. print(n)
  33. n = Null('value', param='value')
  34. print(n)
  35. n()
  36. n('value')
  37. n('value', param='value')
  38. print(n)
  39. # attribute handling
  40. n.attr1
  41. print('attr1', n.attr1)
  42. n.attr1.attr2
  43. n.method1()
  44. n.method1().method2()
  45. n.method('value')
  46. n.method(param='value')
  47. n.method('value', param='value')
  48. n.attr1.method1()
  49. n.method1().attr1
  50. n.attr1 = 'value'
  51. n.attr1.attr2 = 'value'
  52. del n.attr1
  53. del n.attr1.attr2.attr3
  54. # representation and conversion to a string
  55. assert repr(n) == '<Null>'
  56. assert str(n) == 'Null'
  57. if __name__ == '__main__':
  58. test()
  59. ### OUTPUT ###
  60. # Null
  61. # Null
  62. # Null
  63. # Null
  64. # attr1 Null