I am having some trouble with dynamically importing Classes and attempting to run functions in said classes. This is my problem, specifically.
I have a python script dyn_imports.py
in a director called dynamic_imports
. Inside this folder is a subdir called scripts
. In this scripts directory there is an __init__.py
and a python class called AbhayScript.py
. In the class AbhayScript
, there is a function called say_hello()
My objective is: From dyn_imports.py
, I would like to be able to import scripts.AbhayScript
and call the function say_hello()
in AbhayScript
So far, I have attempted a variety of options including __import__
, importlib.import_module
and pydoc.locate
. All of these options give me access to the module
AbhayScript but when I try a getattrs()
or try to call the object, I get an error stating that its not callable or has no attribute.
dyn_imports.py - One of my experiments
myclass = 'scripts.AbhayScript'
import importlib
mymod = importlib.import_module(myclass)
mod,newclass = myclass.rsplit('.',1)
ncls = getattr(mod,newclass) #throws an AttributeError that 'str' object has no attribute
AbhayScript.py code
class AbhayScript(object):
def say_hello(self):
print 'Hello Abhay Bhargav'
The directory structure is as follows
The init.py in the scripts folder is empty.
I have attempted nearly all the solutions in Stackoverflow, but I am a little flummoxed by this one. What am I doing wrong?
Aucun commentaire:
Enregistrer un commentaire