简体   繁体   English

如何从python中的另一个文件调用函数

[英]How to call functions from another file in python

I am not too far into python yet and here is the case. 我对python的了解还不太远,这里就是这种情况。

Say I have one python file called functions.py which holds a class with my functions. 假设我有一个名为functions.py的python文件,其中包含带有我的函数的类。 Below is an example. 下面是一个例子。

import json

class Functionalities:
    def addelement(element):
        # code goes here`

And I have another python file, kind of 'executable' script which does all the job using functions from functions.py class 我还有另一个python文件,一种“可执行”脚本,它使用functions.py类中的函数来完成所有工作

Adding from . import functions from . import functions添加from . import functions from . import functions doesn't help. from . import functions无济于事。

How to I call functions from the class from another file? 如何从另一个文件的类中调用函数?

Unlike java, you don't have to use classes in python. 与Java不同,您不必在python中使用类。 If a class is used only as a holder for functions, chances are that you want a free function (one without a class) instead. 如果一个类仅用作函数的持有人,那么您可能会想要一个自由函数(一个没有类的函数)。

But to answer your actual question, you can use the import statement. 但是要回答您的实际问题,可以使用import语句。 That will run the other .py file, and make the namespace available so you can call things defined there. 这将运行另一个.py文件,并使名称空间可用,以便您可以调用在那里定义的内容。

functions.py : functions.py

import json

class Functionalities:
    def addelement(element):
        # code goes here`

main.py : main.py

import functions
f = functions.Functionalities()
f.addelement('some element')

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM