简体   繁体   English

即使导入成功,Python也找不到类

[英]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.

相关问题 即使安装了软件包,也无法解析 python 导入模块 - Can't resolve python import module even though packages are installed python3即使安装了也无法导入dbus - python3 Can't import dbus even though it's installed 无法导入 Python 模块,即使它在 PYTHONPATH 中 - Can't import Python module even though it is in the PYTHONPATH 即使安装了Python,也找不到PyGObject / gi - Python can't find PyGObject/gi even though it is installed 即使正在导入Python类,也无法实例化它 - Can't instantiate Python class even though it's being imported 即使安装了 pygame 也无法导入 - Can't import pygame even though it is installed pyautogui / pyscreeze 找不到枕头,即使它已成功安装到同一个 package 文件夹中,我可以导入它 - pyautogui / pyscreeze can't find pillow even though it is successfully installed into the same package folder and I can import it django 找不到 url 即使它在那里 - django can't find url even though it is there 即使我有python setup.py开发它也无法按库名导入 - Can't import by library name, even though I have python setup.py develop it Python:我无法导入模块,即使它位于site-packages中 - Python: I can't import a module even though it's in site-packages
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM