virtual_functions.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. # Copyright David Abrahams 2004. Distributed under the Boost
  2. # Software License, Version 1.0. (See accompanying
  3. # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4. '''
  5. >>> from virtual_functions_ext import *
  6. >>> class C1(concrete):
  7. ... def f(self, y):
  8. ... return concrete.f(self, Y(-y.value()))
  9. >>> class C2(concrete):
  10. ... pass
  11. >>> class A1(abstract):
  12. ... def f(self, y):
  13. ... return y.value() * 2
  14. ... def g(self, y):
  15. ... return self
  16. >>> class A2(abstract):
  17. ... pass
  18. >>> y1 = Y(16)
  19. >>> y2 = Y(17)
  20. #
  21. # Test abstract with f,g overridden
  22. #
  23. >>> a1 = A1(42)
  24. >>> a1.value()
  25. 42
  26. # Call f,g indirectly from C++
  27. >>> a1.call_f(y1)
  28. 32
  29. >>> assert type(a1.call_g(y1)) is abstract
  30. # Call f directly from Python
  31. >>> a1.f(y2)
  32. 34
  33. #
  34. # Test abstract with f not overridden
  35. #
  36. >>> a2 = A2(42)
  37. >>> a2.value()
  38. 42
  39. # Call f indirectly from C++
  40. >>> try: a2.call_f(y1)
  41. ... except AttributeError: pass
  42. ... else: print('no exception')
  43. # Call f directly from Python
  44. >>> try: a2.call_f(y2)
  45. ... except AttributeError: pass
  46. ... else: print('no exception')
  47. ############# Concrete Tests ############
  48. #
  49. # Test concrete with f overridden
  50. #
  51. >>> c1 = C1(42)
  52. >>> c1.value()
  53. 42
  54. # Call f indirectly from C++
  55. >>> c1.call_f(y1)
  56. -16
  57. # Call f directly from Python
  58. >>> c1.f(y2)
  59. -17
  60. #
  61. # Test concrete with f not overridden
  62. #
  63. >>> c2 = C2(42)
  64. >>> c2.value()
  65. 42
  66. # Call f indirectly from C++
  67. >>> c2.call_f(y1)
  68. 16
  69. # Call f directly from Python
  70. >>> c2.f(y2)
  71. 17
  72. '''
  73. def run(args = None):
  74. import sys
  75. import doctest
  76. if args is not None:
  77. sys.argv = args
  78. return doctest.testmod(sys.modules.get(__name__))
  79. if __name__ == '__main__':
  80. print("running...")
  81. import sys
  82. status = run()[0]
  83. if (status == 0): print("Done.")
  84. sys.exit(status)