【问题标题】:How can a function from different python module can be used in another defined function?如何在另一个定义的函数中使用来自不同 python 模块的函数?
【发布时间】:2020-05-17 09:10:08
【问题描述】:

在这里,我想在定义的函数 f(v) 中使用模块 FrenselIntegral.py 中的 c(v) 和 s(v)。

import FrenselIntegral as fi

v=0.0
u=0.2

def f(v): 0.5*((0.5-fi.c(v))**2+(0.5-fi.s(v))**2)

file=open("Straightedge diffraction pattern.txt","w")

for i in range (25):
   print>>file,v,f(v)
   v=v+u
file.close()

但是,输出是

Traceback (most recent call last):
  File "c:/Users/Shubhadeep/Desktop/New folder/Straightedge diffraction pattern.py", line 11, in <module>
    print>>file,v,f(v)
  File "c:/Users/Shubhadeep/Desktop/New folder/Straightedge diffraction pattern.py", line 4, in f
    def f(v): 0.5*((0.5-fi.c(v))**2+(0.5-fi.s(v))**2)
TypeError: unsupported operand type(s) for -: 'float' and 'NoneType'

【问题讨论】:

  • 可以添加FresnelIntegral.py的内容吗?在我看来,您的函数 c() 和 s() 缺少返回语句。
  • def c(v):如果 v==0.0 返回 0.00
  • 所以你的函数 c() 对于所有不等于零的 v 值都是空的。你确定这是 c() 的完整定义吗?
  • 不,实际上是 def c(v): if v==0: return 0.00 elif v==0.2: return 0.37 - 这样就这么久了
  • 你能用那个模块的全部内容更新这个问题吗?或者以某种方式链接它?因为那个函数的内容对我来说似乎是个问题。不是您导入模块的方式

标签: python function python-2.6


【解决方案1】:

这点看起来像 fi.c(v) 返回 None。您可以检查 v 的哪些值给出了该结果,或者只是避免 None 返回,例如:

import FrenselIntegral as fi

v=0.0
u=0.2

def f(v):
  if fi.c(v) is None or fi.s(v) is None:
    return 0
  else:
    return 0.5*((0.5-fi.c(v))**2+(0.5-fi.s(v))**2)

file=open("Straightedge diffraction pattern.txt","w")

for i in range (25):
   print>>file,v,f(v)
   v=v+u
file.close()

【讨论】:

    猜你喜欢
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多