You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Since in Line._init__(..) you say self.start = start, self.start is free for change, and in Line.length(..) you must check if Line attrs has changed from the point when DataCache was setted.
Options are:
mark as private self.start -> self._start
or remember hash of relevant data when you set DataCache
If the attributes are considered to be private, the length could be calculated in the constructor and saved as a constant, without using a cache.
=> There should be a setters for the coordinates, resetting the cache.
The __nonzero__ method is not called in python 3. => Rename to __bool__.
import math
class DataCache(object):
""" A class representing cachable data"""
def __init__(self):
self._data = None
def __call__(self):
return self._data
def __bool__(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):
self._data = data
def reset(self):
self._data = None
class Line(object):
"""
This is a class representing a 2D line.
Takes a start point and end point represented by two pairs.
The length is cached, so that it does not need to be re-calculated
as long as the coordinates do not change.
"""
def __init__(self, start, end):
self._start = start
self._end = end
self._length_data = DataCache()
def set_start(start):
self._start = start
self._length_data.reset()
def set_end(end):
self._end = end
self._length_data.reset()
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() # <= this is possible due to __call__ method
Activity
stefaneidelloth commentedon Jan 29, 2021
If the attributes are considered to be private, the length could be calculated in the constructor and saved as a constant, without using a cache.
=> There should be a setters for the coordinates, resetting the cache.
The
__nonzero__method is not called in python 3. => Rename to__bool__.