有很多帖子都有类似的标题,但都没有回答我的问题
我有一个对函数进行分析的代码。函数的定义在一个模块中,例如definition.py
。假设内容是
# module definition.py
def f(x):
return x**2
用于执行分析的所有函数都放在不同的模块中,例如analysis.py
# module analysis.py
def factor2(x):
return 2*f(x)
我希望主代码看起来像这样
# main.py
from definition import *
from analysis import *
print( factor2(3.0) )
并期望看到结果“18.0”
注意,我不想在factor2
的定义中显式地指定函数f
。这是行不通的。编译器说没有定义名称f
我可以将函数factor2定义为factor2(f,x)
,然后传递参数f
。但这正是我试图避免的。这是因为整个代码的目的是只在f
上工作,并且一遍又一遍地编写该f是很乏味的。此外,它使代码更长(如果有许多这样的f和许多分析函数)
有没有办法将f
的定义从definition.py
传递到analysis.py
从analysis.py
内导入definition.py
没有好处,因为我希望能够通过导入不同的模块(例如definition2.py
)来更改f
的定义,而不再接触analysis.py
模块
如a comment中所述,最好使用分部:
例如:
胡安帕还说:
如果你想在课堂上做更多的事情,这是一个很好的选择。否则就太过分了,比如Jack Diederich said:
相关问题 更多 >
编程相关推荐