I've run across a strange issue, and I have not found any similar issues in my searches; which probably means the issue is plainly obvious and I am just not seeing it. I have a class module called modulefile.py, in a folder called modulefolder. Here is modulefile.py:
class moduleclass(object):
def __init__(self):
self.parameter = 5
Now, in my test1.py file I do this:
from modulefolder.modulefile import moduleclass
myobj = moduleclass()
print myobj.parameter
And this works great - it prints the value 5 as expected.
Now, my problem is that in my application I won't know modulefolder, modulefile and moduleclass until runtime. They will be provided to me in strings. So I tried this, this is test2.py:
module = __import__("modulefolder.modulefile", fromlist=["moduleclass"])
myobj = getattr(module, "moduleclass")
print myobj.parameter
And this doesn't work, I get an error AttributeError: type object 'moduleclass' has no attribute 'parameter'.
So, this is what is baffling me. In both test1.py and test2.py I changed the print statment to print dir(myobj) instead, and I get this:
For test1.py:
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'parameter']
For test2.py
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
So, clearly, the second import method is missing my 'parameter' attribute. The problem is, I don't know why.
Why does this method of dynamic import affect the way the instantiated object works? And what can I do to fix it?
I've searched high-and-low looking for answers, so it's probably something straightforward that I've overlooked, or just don't fully understand.
You don't instantiate your class in test2.py:
myobj = getattr(module, "moduleclass")()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With