如何将两个函数打包到一个模块中?

2024-05-16 04:41:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个newtons方法的函数来估计用户输入的数字的根,但是我的任务是“将这些函数打包成一个模块”。我承认我很难理解模块的概念,也找不到任何对我有帮助的材料。你知道吗

尝试将函数分别保存为两个不同的文件并使用import命令,但似乎没有找到任何成功。你知道吗

[编辑]尝试在确定最终估算后使上一个\u x不显示。你知道吗

previous_x

[Edit2]上一个\u x仍显示“无”

enter image description here

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

Tags: 模块文件方法函数用户none概念if
2条回答

您“将函数分别保存为两个不同的文件并使用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)

所以是的,当你开始的时候,这会让人困惑,我同意你的观点。所以让我让它变得超级简单。你知道吗

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

那是我能做的最简单的事了。还有什么问题,你需要看一下文件。但你最好的办法是做实验,用错误的方法去做,直到你用正确的方法去做才是最好的老师。你知道吗

相关问题 更多 >