Advertisement
rfmonk

functools_method.py

Jan 15th, 2014
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. import functools
  5.  
  6.  
  7. class MyClass(object):
  8.     """Demonstration class for functools"""
  9.  
  10.     def method1(self, a, b=2):
  11.         """Docstring for method1()."""
  12.         print ' called method1 with:', (self, a, b)
  13.         return
  14.  
  15.     def method2(self, c, d=5):
  16.         """Docstring for method2"""
  17.         print ' called method2 with:', (self, c, d)
  18.         return
  19.     wrapped_method2 = functools.partial(method2, 'wrapped c')
  20.     functools.update_wrapper(wrapped_method2, method2)
  21.  
  22.     def __call__(self, e, f=6):
  23.         """Docstring for MyClass.__call__"""
  24.         print ' called object with:', (self, e, f)
  25.         return
  26.  
  27.  
  28. def show_details(name, f):
  29.     """shows details of a callable object."""
  30.     print '%s:' % name
  31.     print ' object:', f
  32.     print ' __name__:',
  33.     try:
  34.         print f.__name__
  35.     except AttributeError:
  36.         print '(no __name__)'
  37.     print ' __doc__', repr(f.__doc__)
  38.     return
  39.  
  40. o = MyClass()
  41.  
  42. show_details('method1 straight', o.method1)
  43. o.method1('no default for a', b=3)
  44. print
  45.  
  46. p1 = functools.partial(o.method1, b=4)
  47. functools.update_wrapper(p1, o.method1)
  48. show_details('method1 wrapper', p1)
  49. p1('a goes here')
  50. print
  51.  
  52. show_details('wrapped method2', o.wrapped_method2)
  53. o.wrapped_method2('no default for c', d=6)
  54. print
  55.  
  56. show_details('instance', o)
  57. o('no default for e')
  58. print
  59.  
  60. p2 = functools.partial(o, f=7)
  61. show_details('instance wrapper', p2)
  62. p2('e goes here')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement