简体   繁体   English

如何在另一个python文件中使用函数

[英]How to use a function in another python file

I made a function called WaveLengthCal(d, T) as below 我做了一个叫做WaveLengthCal(d,T)的函数,如下所示

def WaveLengthCal(d, T):

 import numpy as np

 g=9.8
 k0h=4*np.pi**2/g/T**2*d;

 if k0h>2.72:
    kh=k0h*(1+2*np.exp(-2*k0h))
 else:
    kh=np.sqrt(k0h)*(1+1/16*k0h+11/360*k0h**2)

 NP=10 # number of time of iteration
 L0=g*T**2/2/np.pi
 L=L0*np.tanh(kh)

 if d/L <1/20:
    L=T*np.sqrt(g*d)
 elif d/L>1/2:
    L=L0
 else:
    for i in range(NP):
        L=g*T**2/2/np.pi*np.tanh(2*np.pi*d/L)

 return L

This function works fine if I use this function in the same file as 如果我在与以下文件相同的文件中使用此功能,则此功能正常工作

>>> WaveLengthCal(2,3)
[11.297788563155367]

However, when I tried to use this function in another python file as below, 但是,当我尝试在下面的另一个python文件中使用此功能时,

import WaveLengthCal as wl

L=wl.WaveLengthCal(0.513,2)

it does not work well, it showed an error message as 它不能很好地工作,它显示一条错误消息为

> Traceback (most recent call last):   File
> "/usr/lib/python3.5/code.py", line 91, in runcode
>     exec(code, self.locals)   File "<input>", line 7, in <module> TypeError: WaveLengthCal() missing 1 required positional argument: 'T'

I am not sure why, as I already put two inputs there, but it keeps on telling me one of the argument is missing. 我不确定为什么,因为我已经在其中输入了两个输入,但是它不断告诉我缺少一个论点。 Anyone has any suggestions? 有人有建议吗?

What is the name of the file into which you put your function? 您将函数放入其中的文件的名称是什么? It is that name that should be imported. 应该输入的是该名称。 Say: 说:

You have a file named: wavefunctionfile.py with the following content: 您有一个名为: wavefunctionfile.py的文件,其内容如下:

def wavefunction(a,b):
    print(a)
    print(b)
    return a+b

You can now start python in the same directory as the file and do this: 现在,您可以在与文件相同的目录中启动python并执行以下操作:

>>> import wavefunctionfile as w
>>> w.wavefunction(3,4)

This will output 这将输出

3
4
7

from WaveLengthCalFile import WaveLengthCal should work, but I feel like if the above doesn't work then there is something else going on... from WaveLengthCalFile import WaveLengthCal应该可以,但是我觉得如果以上方法不起作用,那么还会有其他事情发生……

Note that you will need to configure your IDE to work with this. 请注意,您将需要配置IDE才能使用它。 In Pycharm you can right click the directory your WaveLengthCalFile is in and click "Mark as Source" 在Pycharm中,您可以右键单击WaveLengthCalFile所在的目录,然后单击“标记为源”

有关更多信息,请参见此图片

In the above picture, I import a function called a_func from a file called moonbase.py, which demonstrates your required functionality exactly 在上图中,我从名为a_func的文件中导入了一个名为a_func的函数,该函数完全演示了您所需的功能

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

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