Home > Backend Development > Python Tutorial > Can python reference a function of another file?

Can python reference a function of another file?

anonymity
Release: 2019-06-15 14:16:58
Original
7176 people have browsed it

In python, you can reference the function of another file. Here is an example: First, the calling method in the same folder is as follows:

Can python reference a function of another file?

Call the function :

A.py:
def add(x,y):
    print('和为:%d'%(x+y))
Copy after login

B.py file:

import A
A.add(1,2)
 
###或者###
from A import add
add(1,2)
Copy after login

If not in a folder:

import sys
sys.path.append(r'E:\PythonProject\winycg')
Copy after login

' ''When python imports the module, it is searched in sys.path in order.

sys.path is a list that stores many paths in the form of strings.

To use the function in the A.py file, you need to first put its file path in sys.path'''

import A
 
a=A.A(2,3)
a.add()
Copy after login

Sometimes, it will prompt ## during execution #No module named "xxx", referring to the __init__.py file for modification still cannot achieve the desired effect. Therefore, in this case, the following methods have been tried to achieve the goal.

When the .py file to be referenced is not in the same folder as the file currently being executed, we can still implement it directly using the third line of code below. You can see that the first two lines are commented out.

#import sys
#sys.path.append(r'D:\Python27\Pythonfiles\HMM')
from Pythonfiles.HMM import M_matrix  ##引用M矩阵
Copy after login

The above M_matrix.py file converts the time series into a certain matrix form, which makes it easier for us to read different files and represent the M matrix into a file. At this time, the parameters can be called Refer to the following form:

def matrix(X):
    par = M_matrix.parameters(X)
    M = M_matrix.center(X, par[5], par[6], par[7], par[8], par[9])  # 获取转换后的M矩阵
    return M
Copy after login

The above is the detailed content of Can python reference a function of another file?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template