如何使用另一个.py文件中的类方法? [英] How to use class methods from another .py file?

查看:176
本文介绍了如何使用另一个.py文件中的类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是文件结构都在同一个文件夹中:

Following is the file structure all are in same folder:

__ init__.py
gnewsclient.py
test .py

1)
__ init__.py:

来自.gnewsclient import gnewsclient

2) gnewsclient.py

class gnewsclient:
//某些方法

现在我要从gnewsclient类中导入 gnewsclient.py 文件中的方法 test.py

Now I want to import methods from gnewsclient class of gnewsclient.py file inside test.py

我从gnewsclient import * 尝试了但是它表示未加载父模块''无法执行相对导入。

I tried from gnewsclient import * but it says parent module not loaded '' cannot perform relative import.

推荐答案

包布局:

 package
    | __init__.py
    | module1.py
    | module2.py

 script.py

如果要导入函数 f1 来自 module1 in module2 do:
来自package.module1 import f1

If you want to import a function f1 from module1 in module2 do:
from package.module1 import f1.

现在,如果你尝试执行 module2.py 通过执行 python module2.py ,它将无法工作,因为你在包内,所以python找不到模块的路径和你会遇到那种错误。因此,如果您想使用或测试您的模块,您需要在包外部进行,例如 script.py

Now, if you try to execute module2.py by doing python module2.py, it won't work because you are inside the package, so python does not find the path to the module and you will have the kind of error you got. So if you want to use or test your modules, you need to do it from outside the package, in script.py for instance:

示例:script.py

from package.module1 import f1
from package.module2 import f2

print(f1())
print(f2())

这篇关于如何使用另一个.py文件中的类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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