paul@2 | 1 | class C: |
paul@2 | 2 | def c(self): |
paul@2 | 3 | return 1 |
paul@2 | 4 | |
paul@266 | 5 | class D(C): |
paul@2 | 6 | def d(self): |
paul@2 | 7 | return 3 |
paul@2 | 8 | |
paul@2 | 9 | a = 4 |
paul@266 | 10 | l = [] |
paul@2 | 11 | |
paul@2 | 12 | def f(x): |
paul@266 | 13 | |
paul@266 | 14 | # Test global mutation. |
paul@266 | 15 | |
paul@266 | 16 | l.append(x.c()) |
paul@266 | 17 | |
paul@266 | 18 | # Test function initialisation. |
paul@266 | 19 | |
paul@43 | 20 | def g(y, x=x): # x must be introduced as default here |
paul@2 | 21 | if y: |
paul@2 | 22 | x = D() |
paul@2 | 23 | return x.d(), y, a # UnboundLocalError in Python (if y is a false value) |
paul@266 | 24 | |
paul@2 | 25 | return g |
paul@2 | 26 | |
paul@266 | 27 | # Provide a default instance for a function to be obtained. |
paul@266 | 28 | |
paul@266 | 29 | fn = f(C()) |
paul@266 | 30 | print l # [1] |
paul@266 | 31 | print fn # __main__.f.$l0 |
paul@266 | 32 | try: |
paul@266 | 33 | print fn(2) # should fail due to g requiring an object providing d |
paul@266 | 34 | except TypeError: |
paul@266 | 35 | print "fn(2): fn initialised with an inappropriate object" |
paul@266 | 36 | |
paul@266 | 37 | try: |
paul@266 | 38 | print fn(0) # should fail due to g requiring an object providing d |
paul@266 | 39 | except TypeError: |
paul@266 | 40 | print "fn(0): fn initialised with an inappropriate object" |
paul@266 | 41 | |
paul@266 | 42 | # Override the default when calling the function. |
paul@266 | 43 | |
paul@266 | 44 | print fn(2, D()) # (3, 2, 4) |
paul@266 | 45 | print fn(0, D()) # (3, 0, 4) |
paul@266 | 46 | |
paul@266 | 47 | # Provide a more suitable default instance for the function. |
paul@266 | 48 | |
paul@266 | 49 | fn = f(D()) |
paul@266 | 50 | print l # [1, 1] |
paul@266 | 51 | print fn(2) # (3, 2, 4) |
paul@266 | 52 | print fn(0) # (3, 0, 4) |
paul@266 | 53 | print fn(0, D()) # (3, 0, 4) |
paul@266 | 54 | |
paul@266 | 55 | # Override with an unsuitable object even though it would be ignored. |
paul@266 | 56 | |
paul@266 | 57 | try: |
paul@266 | 58 | print fn(1, C()) |
paul@266 | 59 | except TypeError: |
paul@266 | 60 | print "fn(1, C()): an unsuitable argument was given." |
paul@266 | 61 | |
paul@266 | 62 | # Override with an unsuitable object. |
paul@266 | 63 | |
paul@266 | 64 | try: |
paul@266 | 65 | print fn(0, C()) |
paul@266 | 66 | except TypeError: |
paul@266 | 67 | print "fn(0, C()): an unsuitable argument was given." |