Python: Dynamically call function within abstract class -
i have class instance needs call analyse method. constructor receives request object kind of message
{ "message":{ "attributes":{ "message_id":"2aj78h98-2112-4637-76h1-09ec727933bb", "topic":"mytopic", "version":1 }, "data":"{"id": 123541234}" } }
my_model = mymodel(request) my_model.analyse(data)
the structure of class mymodel is:
import importlib class mymodel(object): def __init__(self, req): """ request, extract topic , dynamically create instance """ try: self.req = req classname = self.req.topic # in example: mytopic classpath = 'foo.bar' module = importlib.import_module(classpath) self.some_object = getattr(module, classname) except exception e: raise exception(e.message) def analyse(self): data = self.req.data # self.some_object instance of foo.bar.mytopic self.some_object.analyse(data)
here structure of mytopic class:
class mytopic(topicbase): def __init__(self): super(mytopic, self).__init__() self.retreive_mode = 'api' def _retreive_from_db(self): print 'in db' def _retreive_from_datawarehouse(self): print 'in datawarehouse' def _retreive_from_api(self): print 'in api
and parent class:
from abc import abcmeta, abstractmethod class topicbase(object): __metaclass__ = abcmeta def __init__(self, *args, **kwargs): pass def analyse(self, data): """ base on class configuration, call proper retreive method """ def func_not_found(): # in case dont have method raise notimplementederror func_name = '_retreive_from_' + self.retreive_mode func = getattr(self, func_name, func_not_found) func(data) @abstractmethod def _retreive_from_db(self): pass @abstractmethod def _retreive_from_datawarehouse(self): pass @abstractmethod def _retreive_from_api(self): pass
when my_model.analyse(data) called, error:
typeerror: unbound method analyse() must called mytopic instance first argument (got dict instance instead)
my_model instance of mytopic. if try my_model.analyse(my_model, data), got error:
typeerror: unbound method analyse() must called mytopic instance first argument (got abcmeta instance instead)
any idea??
this
self.some_object = getattr(module, classname)
sets self.some_object
class (not instance of class), means when mymodel.analyse()
calls
self.some_object.analyse(data)
it's calling someclass.analyse(data)
, not someclass().analyse(data)
.
Comments
Post a Comment