Yves
Yves

Reputation: 12371

python: how to import a module

I'm a newbie in using Python.
What I need is simple: import a module dynamically.

Here is my little test:

#module
class Test:
    def func(self, id, name):
        print("Your ID: " + str(id) + ". Your name: " + name)
        return

I put this class in a file named my_module.py and the path of the file is: c:\doc\my_module.py.

Now I create a new python project to import the file above.

Here is what I do:

import sys
module = sys.path.append(r'c:\doc\my_module.py')
myClass = module.__class__
print(myClass)

However, I got this result:

<class 'NoneType'>

Why can't I get Test?

Is it because the way to import a module is wrong or because I need to do some config to import a module?

Upvotes: 1

Views: 285

Answers (3)

user2750362
user2750362

Reputation: 382

The way to import a module is through the import command. You can specify the path with sys as a directory. You also need to instantiate the class within the module (through the my_module.Test()). See the following:

import sys
sys.path.append(r'c:\doc\\')
import my_module

myObj = my_module.Test()
myClass = myObj.__class__
print(myClass)

Upvotes: 1

Nhor
Nhor

Reputation: 3940

You're doing it wrong. Here's how you should import your module with sys.path.append:

import sys                    # import sys
sys.path.append(r'c:\doc\')   # add your module path to ``sys.path``
import my_module              # now import your module using filename without .py extension
myClass = my_module.Test      # this is how you use the ``Test`` class form your module

Upvotes: 2

Fujiao Liu
Fujiao Liu

Reputation: 2253

try this:

import sys
sys.path.append(r'c:\doc\')  # make sure python find your module

import my_module    # import your module 

t = my_module.Test() # Initialize the Test class
t.func(1, 'test')  # call the method

Upvotes: 1

Related Questions