[英]Python can't find class even though the import was successful
I have some folder: /home/tom/my_module
. 我有一些文件夹: /home/tom/my_module
。
In my_module directory I have: 在my_module目录中,我有:
__init__.py
(empty file) __init__.py
(空文件)
my_class.py
class HelloWorldExample(object):
@staticmethod
def someMethod():
print("test")
Now, let's go into terminal terminal: 现在,让我们进入终端终端:
cd ~ python
And then, in python shell: 然后,在python shell中:
import my_module
succedeed. import my_module
成功。 However, I can't type something like: 但是,我不能输入以下内容:
x= HelloWorldExample()
nor 也不
HelloWorldExample.someMethod()
because python can't find this class. HelloWorldExample.someMethod()
因为python找不到此类。
Any ideas? 有任何想法吗?
When doing import my_module
you're importing the module and it will be available as my_module
. import my_module
您正在导入模块,它将作为my_module
可用。
If you want to access something defined in your module you will need to access it on the module ex: my_module.thing_in_my_module
. 如果要访问模块中定义的内容,则需要在模块my_module.thing_in_my_module
上访问它。
In your example that would translate to: 在您的示例中,这将转换为:
import my_module
x = my_module.HelloWorldExample()
But you could also do: 但是您也可以这样做:
from my module import HelloWorldExample
x = HelloWorldExample()
This imports the class directly rather than the module. 这将直接导入类而不是模块。
See https://docs.python.org/3/tutorial/modules.html#packages for more information on packages and imports. 有关包和导入的更多信息,请参见https://docs.python.org/3/tutorial/modules.html#packages 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.