Lichen

tests/methods_rebound.py

1047:101519d4e2c2
5 months ago Paul Boddie Employ generic operations instead of operator method calls.
     1 class C:     2     def f(self):     3         print self     4         return self.value()     5      6     def value(self):     7         return 123     8      9 c = C()    10     11 class D:    12     f = c.f    13     14 d = D()    15     16 def fn():    17     return 456    18     19 class E:    20     f = fn    21     g = C.f    22     23 e = E()    24     25 # Normal method access and invocation.    26     27 print c.f.__name__                  # f    28 print c.f()                         # <__main__.C instance>    29                                     # 123    30     31 # Access and call assigned bound method.    32     33 print d.f.__name__                  # wrapper    34 print d.f()                         # <__main__.C instance>    35                                     # 123    36     37 # Access and call assigned function.    38     39 print e.f.__name__                  # fn    40 print e.f()                         # 456    41     42 # Access details of assigned method.    43     44 print e.g.__name__                  # f    45     46 # Attempt to call method belonging to another class via an incompatible    47 # instance. In Python, this would be an unbound method call attempt.    48     49 try:    50     print e.g()    51 except TypeError:    52     print "e.g(): e is an incompatible instance for E.g which is C.f"    53     54 g = get_using(E.g, c)    55 print g.__name__                    # f    56 print g()                           # <__main__.C instance>    57                                     # 123