null.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/user/bin/env python
  2. """http://code.activestate.com/recipes/68205-null-object-design-pattern/"""
  3. class Null:
  4. def __init__(self, *args, **kwargs):
  5. """Ignore parameters."""
  6. return None
  7. def __call__(self, *args, **kwargs):
  8. """Ignore method calls."""
  9. return self
  10. def __getattr__(self, mname):
  11. """Ignore attribute requests."""
  12. return self
  13. def __setattr__(self, name, value):
  14. """Ignore attribute setting."""
  15. return self
  16. def __delattr__(self, name):
  17. """Ignore deleting attributes."""
  18. return self
  19. def __repr__(self):
  20. """Return a string representation."""
  21. return "<Null>"
  22. def __str__(self):
  23. """Convert to a string and return it."""
  24. return "Null"
  25. def test():
  26. """Perform some decent tests, or rather: demos."""
  27. # constructing and calling
  28. n = Null()
  29. print(n)
  30. n = Null('value')
  31. print(n)
  32. n = Null('value', param='value')
  33. print(n)
  34. n()
  35. n('value')
  36. n('value', param='value')
  37. print(n)
  38. # attribute handling
  39. n.attr1
  40. print('attr1', n.attr1)
  41. n.attr1.attr2
  42. n.method1()
  43. n.method1().method2()
  44. n.method('value')
  45. n.method(param='value')
  46. n.method('value', param='value')
  47. n.attr1.method1()
  48. n.method1().attr1
  49. n.attr1 = 'value'
  50. n.attr1.attr2 = 'value'
  51. del n.attr1
  52. del n.attr1.attr2.attr3
  53. # representation and conversion to a string
  54. assert repr(n) == '<Null>'
  55. assert str(n) == 'Null'
  56. if __name__ == '__main__':
  57. test()