无法从模块导入方法 [英] Cannot import a method from a module

查看:30
本文介绍了无法从模块导入方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从python模块中导入方法,但得到的结果将引发下面提到的错误.

I'm trying to import a method from a python module but getting it's throwing an error mentioned below.

无法从模块名称"导入名称方法名称"

我的目录结构:

有解决此问题的方法,但在我看来,这些解决方案已得到满足.下面是我尝试从模块中导入方法的方法.

there are solutions to this problem but those are already satisfied in my case. Below is how I tried to import the method from the module.

从text_preprocessing导入TextToTensor,clean_text

此处 TextToTensor 是类名,而 clean_text 是TextToTensor类中的方法.

here TextToTensor is aclass name and clean_text is a method in TextToTensor class.

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

of Course, I can create an instance of TextToTensor and use to call the clean_text method, but I'm desperate to import the function.

提前谢谢.

推荐答案

我认为您有以下选择:

文件 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())

替代项一/二产生一个 class方法/静态方法,该方法不需要 MyClass instance >上班.仅当函数的定义不涉及 self.xyz 时才可行(实际上,这样的定义会产生错误).

Alternative one/two produces a class method/static method that doesn't need an instance of MyClass to work. This is only viable if the definition of the functions doesn't involve self.xyz (in fact, such defintions would produce an error).

第三个替代方法很简单:在 test.py 中定义函数,然后将其用于 MyClass 的相应方法的定义中.由于您说的是您绝不愿意导入该功能",那可能是要走的路.

The third alternative is simple: Define the function inside test.py and then use it in the definition of the corresponding method of MyClass. Since you said "you're desparate to import the function" that might be the way to go.

这篇关于无法从模块导入方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆