2019-05-20 | Paul Boddie | file changeset files shortlog | Experiment with a temporary attribute on objects. This attribute must be cleared when assignments occur, but it should also be cleared when objects escape from functions (which is not yet done). Since the motivation for marking objects as temporary is their re-use in certain operations, the objective is to avoid objects being used in multiple places and still being marked as temporary and potentially undergoing re-use/mutation. Perhaps the only way of guaranteeing exclusive access to an object is if it is provided as a function result and is immediately passed to a function or operation, with this function either mutating the object or ensuring its direct propagation to another such function. | temporary-object-experiment |
paul@588 | 1 | class C: |
paul@588 | 2 | def __init__(self, x): |
paul@588 | 3 | self.x = x |
paul@588 | 4 | |
paul@588 | 5 | def value(self): |
paul@588 | 6 | return self.x |
paul@588 | 7 | |
paul@588 | 8 | def length(self): |
paul@588 | 9 | return self.double(self.value()) |
paul@588 | 10 | |
paul@588 | 11 | def double(self, x): |
paul@588 | 12 | return x * 2 |
paul@588 | 13 | |
paul@588 | 14 | c = C(3) |
paul@588 | 15 | print c.length() # 6 |
paul@858 | 16 | |
paul@858 | 17 | # Explicit function for addition purposes. |
paul@858 | 18 | |
paul@858 | 19 | def combine(x, y, z): |
paul@858 | 20 | return x + y + z |
paul@858 | 21 | |
paul@858 | 22 | class Tree: |
paul@858 | 23 | def __init__(self, item, left=None, right=None): |
paul@858 | 24 | self.item = item |
paul@858 | 25 | self.left = left |
paul@858 | 26 | self.right = right |
paul@858 | 27 | |
paul@858 | 28 | def count(self): |
paul@858 | 29 | if self.left and self.right: |
paul@858 | 30 | # Test calls in parameter lists needing separate temporary storage. |
paul@858 | 31 | return combine(self.item, self.left.count(), self.right.count()) |
paul@858 | 32 | else: |
paul@858 | 33 | return self.item |
paul@858 | 34 | |
paul@858 | 35 | tree = \ |
paul@858 | 36 | Tree(10000, |
paul@858 | 37 | Tree(2000, |
paul@858 | 38 | Tree(300), |
paul@858 | 39 | Tree(40) |
paul@858 | 40 | ), |
paul@858 | 41 | Tree(5)) |
paul@858 | 42 | |
paul@858 | 43 | print tree.count() # 12345 |