简体   繁体   English

python:如何导入模块

[英]python: how to import a module

I'm a newbie in using Python. 我是使用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 . 我将此类放在名为my_module.py的文件中,文件的路径为: c:\\doc\\my_module.py

Now I create a new python project to import the file above. 现在,我创建一个新的python项目以导入上面的文件。

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 ? 为什么我不能参加Test

Is it because the way to import a module is wrong or because I need to do some config to import a module? 是因为导入模块的方法错误还是因为我需要做一些配置才能导入模块?

You're doing it wrong. 你这样做是错的。 Here's how you should import your module with sys.path.append : 这是使用sys.path.append导入模块的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

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

The way to import a module is through the import command. 导入模块的方法是通过import命令。 You can specify the path with sys as a directory. 您可以使用sys作为目录指定路径。 You also need to instantiate the class within the module (through the my_module.Test()). 您还需要实例化模块中的类(通过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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM