简体   繁体   English

如何使用另一个.py文件中的类方法将两个文件放在同一个程序包中,并且两个文件都放在不同的文件夹中?

[英]How to use class methods from another .py file both files in same package and when both are in different folders?

Case1: Following is the file structure all are in same folder: 情况1:以下是所有文件结构都在同一文件夹中:

`Folder1
    |__init__.py
    |gnewsclient.py
    |test.py
    |utils.py`

1)Content of 
__init__.py

`from .gnewsclient import gnewsclient`

2) Content of client.py

`class gnewsclient:
      //Some methods
`

3)Content of `utils.py`

Some Dictionaries inside utils.py

4)Content of `test.py`:
    Here I want to import methods from client.py which has gnewsclient class()


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

All are in same folder above

In `test.py`:

I tried  

`from client import *` 

or

`from .client import gnewsclient`

but it says parent module not loaded '' cannot perform relative import. 但是它说未加载的父模块“无法执行相对导入。

Case2: Also now if I make a folder2 which has test.py inside it and try to do same importing still it gives no parent module cannot perform relative import. 情况2:同样,现在,如果我制作一个其中包含test.py的folder2并尝试执行相同的导入操作,则仍然没有任何父模块无法执行相对导入。

Content of gnewsclient.py gnewsclient.py的内容

class baby():
    def method(self):
        print 'Method call'

Content of test.py test.py的内容

from gnewsclient import baby # from file_name.py import class_name

b = baby()
b.method()

python test.py python test.py

Output 产量

Method call 方法调用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从another.py调用Python代码? (当我按空格键时 both.py 在同一个文件中) - How to call Python code from another .py? (when I press space bar both .py are in the same file) 如何从相同的python脚本运行.py和.exe文件 - how to run both a .py and a .exe file from the same python script 从另一个py文件的类导入方法时重复的结果 - Duplicated results when importing methods from a class of another py file 鸭子打字和类方法(或者,如何使用类和实例中的方法?) - Duck typing and class methods (or, how to use a method from both a class and an instance?) python:如何独立于入口点读取文件(笔记本和 .py 文件) - python: How to read file independent from entry point (both notebook and .py files) 在同一方法中使用两个父方法 - Use both parents methods in the same method 如何创建一个类似List的类,该类允许在与py2和py3一起使用的切片上调用包含的对象方法 - How to create a List like class which allows calling contained objects methods on slices which work with both py2 and py3 如何将找到的正则表达式字符串从一个文件复制到另一个文件,同时保持两个文件的结构? - How do I copy regex found strings from one file to another, maintaining the structure of both files? 当两者都有不同格式的索引时,如何将一个 DataFrame 的列添加到另一个 - How do I add a column from one DataFrame to another when both have index in different formats 如何将 python 文件导入另一个 python 文件,其中两个文件都没有类并且位于同一目录下? - How do I import a python file into another python file where both files do not have classes and are under the same directory?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM