-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathDataCaching.py
More file actions
68 lines (56 loc) · 1.83 KB
/
Copy pathDataCaching.py
File metadata and controls
68 lines (56 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env python
# Written by: DGC
# python imports
import math
#==============================================================================
class DataCache(object):
def __init__(self):
""" A class representing cachable data, starts invalid."""
self.data = None
def __call__(self):
"""
When an instance is called it returns the stored data or None if no
data has been cached.
e.g
data = cached_data()
"""
return self.data
def __nonzero__(self):
"""
Called on bool(instance) or if(instance) returns if there is data
cached.
e.g
if (not data):
# set data
"""
return self.data is not None
def set(self, data):
""" Sets the data. """
self.data = data
def reset(self):
""" Returns the class to an invalid state. """
self.data = None
#==============================================================================
class Line(object):
def __init__(self, start, end):
"""
This is a class representing a 2D line.
Takes a start point and end point represented by two pairs.
"""
self.start = start
self.end = end
self.length_data = DataCache()
def length(self):
if (not self.length_data):
x_length = self.start[0] - self.end[0]
y_length = self.start[1] - self.end[1]
length = math.sqrt((x_length ** 2) + (y_length ** 2))
self.length_data.set(length)
else:
print("Cached value used")
return self.length_data()
#==============================================================================
if (__name__ == "__main__"):
l = Line((0, 0), (1, 0))
print(l.length())
print(l.length())