我有两个用于newton方法的函数来估计用户输入的数字的根,但我的任务是“将这些函数打包到一个模块中”。我承认我正在努力理解模块的概念,并且找不到任何对我有帮助的材料。
我尝试将函数分别保存为两个不同的文件,并使用import命令,但似乎找不到任何成功。
编辑尝试使previous_x在最终估计建立后不显示。
对于previous_x,Edit2仍然显示"None“
def newtons_fourth(y):
x=1
N=0
previous_x = None
while N < 50:
x=1/4*(3*(x) + y/(x**3))
N=N+1
print('Iteration number:',N)
print('Estimation:',x)
print('Previous x:',previous_x)
print()
if previous_x is not None:
if abs(x - previous_x) < 0.0001:
final=1
print('Difference negligible')
print('Final Estimation:',x)
break
previous_x = x
if final!=1:
return previous_x
发布于 2019-02-07 21:07:16
您的“将函数分别保存为两个不同的文件并使用import命令”的想法是正确的。这里有一种方法可以做到:
CubedModule.py
def newtons_cubed(y):
x=1
N=0
previous_x = None
while N < 50:
x=1/3*(2*(x) + y/(x**2))
N=N+1
print('Iteration number:',N)
print('Estimation:',x)
print('Previous x:',previous_x)
print()
if previous_x is not None:
if abs(x - previous_x) < 0.0001:
print('Difference negligible')
print('Final Estimation:',x)
return
previous_x = x
print(previous_x)
FourthModule.py
def newtons_fourth(y):
x=1
N=0
previous_x = None
final = None
while N < 50:
x=1/4*(3*(x) + y/(x**3))
N=N+1
print('Iteration number:',N)
print('Estimation:',x)
print('Previous x:',previous_x)
print()
if previous_x is not None:
if abs(x - previous_x) < 0.0001:
final=1
print('Difference negligible')
print('Final Estimation:',x)
return
previous_x = x
if final!=1:
print(previous_x)
然后在名为script.py
的主模块中,将每个模块导入到顶部的单独名称空间中,并分别引用它们:
import CubedModule as cm
import FourthModule as fm
y= int(input('Enter value for estimations:'))
print()
print('Cubed root estimation:')
print()
cm.newtons_cubed(y)
print()
print('Fourth root estimation:')
print()
fm.newtons_fourth(y)
发布于 2019-02-07 20:48:40
所以,是的,当你开始的时候,这会让你感到困惑,在这一点上,我同意你的观点。所以让我让它变得超级简单。
python中的函数def
是包含代码的容器。它们运行一次并完成。类是在内部包含一组函数(称为方法)的实例,这些函数可以操作类内部的数据,直到类关闭或程序使用命名实例完成为止。
x = Classname() #creates an instance of the class now named x
x.start() # runs the function start inside the class. Can pass variables, or use existing variables under the self. notation.
模块是包含函数或类的文件。所有模块都已导入。
import os
from os import getcwd #function or class inside the modeul
然后可以这样调用它们:
print(os.getcwd())
print(getcwd())
可以导入任何.py文件。如果目录中包含名为__init__.py
的文件,则可以导入该目录。该文件可以为空。然后,目录名变成模块名,单个文件是像这样导入的子模块:
import myfolder.mymodule
from myfolder import mymodule # the same as above
这是我能做的最简单的事情了。如果还有其他问题,您需要查看文档。但你最好的办法就是去尝试,用错误的方法去做,直到你用正确的方法去做,这才是最好的老师。
https://stackoverflow.com/questions/54581783
复制相似问题