无法从模块导入方法

Cannot import a method from a module

我正在尝试从 python 模块导入一个方法,但在获取它时抛出了下面提到的错误。

cannot import name 'methodname' from 'modulename'

我的目录结构:

这个问题有解决方案,但我已经满意了。 下面是我尝试从模块导入方法的方法。

from text_preprocessing import TextToTensor, clean_text

这里TextToTensor是一个class名字,clean_text是TextToTensor中的一个方法class.

当然,我可以创建一个 TextToTensor 的实例并用于调用 clean_text 方法,但我非常想导入该函数。

提前致谢。

这篇 thread 或许能解决您的问题。

您的 python 代码无法导入模块,因为您没有正确设置导入功能(或文件夹结构,具体取决于您的偏好)。

from text_preprocessing import TextToTensor.clean_text as clean_test

也许这会解决您的问题

尝试导入:

from text_preprocessing import TextToTensor

之后,尝试执行以下操作:

TextToTensor.clean_text(...)

这里的问题是 Python 无法导入带点的名称:

(base) fathead:tmp sholden$ cat module.py
class One:
    def meth(self):
        return 42

(base) fathead:tmp sholden$ python
Python 3.6.10 |Anaconda, Inc.| (default, Jan  7 2020, 15:01:53)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from module import One.meth
  File "<stdin>", line 1
    from module import One.meth
                          ^
SyntaxError: invalid syntax

正确的方法是导入 class。然后,您可以根据需要为其建立一个本地名称。在我的简单示例中,这看起来像

from module import One

my_func = One.meth

但是请注意,my_func_ 一个函数(即它不与任何实例相关联),但它的第一个参数将是 self除非它被定义为 class 方法或静态方法,因此您需要提供一个 One 实例作为调用它的第一个参数。

确定你需要这个功能吗?

我认为你有以下选择:

文件test.py:

class MyClass:

    @classmethod
    def my_method(cls):
        return "class method"

    @staticmethod
    def my_other_method():
        return "static method"

    def yet_another_method(self):
        return yet_another_method()

# Class definition ends here. You can now define another function that
# can be imported like you want to do it, and, if needed, used to define
# a class method of the same name.

def yet_another_method():
    return "works too"

然后在文件中main.py:

from test import MyClass, yet_another_method

print(MyClass.my_method())
function = MyClass.my_method
print(function())

print(MyClass.my_other_method())
function = MyClass.my_other_method
print(function())

print(yet_another_method())

备选 one/two 生成不需要 class 方法/静态方法 MyClass 的 25=] 实例 开始工作。这仅在函数的定义不涉及 self.xyz 时才可行(事实上,这样的定义会产生错误)。

第三种方案很简单:在test.py里面定义函数,然后在MyClass对应方法的定义中使用。既然你说“你很想导入这个函数”,那可能就是正确的方法。