So I'm looking into having a main class that defines a specific method and an extended class that adds some functionality to that method, such as:
class SuperClass:
def __init__(self):
self._data = {}
@abc.abstractmethod
def _get_obj(self, id):
pass
def get(self, obj_id):
# do stuff that should be done for all methods, eg.
if obj_id not in self.data:
obj= self._get_obj(obj_id)
self.data[obj_id] = obj
return self.data[obj_id]
class SubClass(SuperClass):
def _get_obj(self, obj_id):
pass
The idea is that the get
method is the only "public" one. Is there a better way to do this?
For clarity I've only shown one of the "public" methods, but there may be many.
For reference, this is using Python 3.6. And any other comments regarding the code are welcome.
Update (also code cleanup): Another approach is to use super
to call the original get
which may be clearer, but forces the coder to always need to add the call there:
class SuperClass:
def __init__(self):
self._data = {}
def get(self, obj_id):
# do stuff that should be done for all methods, eg.
if obj_id in self.data:
return self.data[obj_id]
pass
class SubClass(SuperClass):
def get_from_db(self, obj_id):
# Code to get from db
return obj
def get(self, obj_id):
obj = super().get(obj_id
if None:
obj= self.get_from_db(obj_id)
self.data[obj_id] = obj
return obj