如何在不出现属性错误的情况下将两个python文件导入到一个文件中?

时间:2019-06-18 10:16:09

标签: python python-import

我正在尝试设置数学方程式计算器。它计算2D形状的面积/周长,3D形状的体积/表面积等。我尝试执行此操作的方法是为每个部分创建一个新的python文件,这样我就没有一个大文件。

问题是,每当我尝试将其他文件(都在同一个文件夹中)导入单个主菜单文件时,如果尝试从其中一个文件调用函数,就会收到属性错误,提示我导入的“模块”没有我刚导入的功能。

AttributeError:模块'TwoDShapeMenu'没有属性'twodshapes'

我尝试创建一个仅在调用时才导入文件的函数,但是我仍然遇到相同的错误,我不知道该怎么办...

我将到目前为止创建的两个文件导入了主程序文件的顶部,仍然是相同的错误。

我已经尝试过对它进行编码,以便仅当在IF语句中选择了选项时才导入两个文件。

我不知道该怎么办。

主文件

def main():
    print(
        "Please choose something from the list below: \n 1.Area/Perimeter of 2D Shapes \n 2.Volume/Surface area of 3D Shapes \n ")
    answer = input()

    if answer == "1":
        import TwoDShapeMenu
        TwoDShapeMenu.twodshapes()

    if answer == "2":
        import ThreeDShapeMenu
        ThreeDShapeMenu.threedshapes()

    else:
        while answer != "1" or "2":
            print("Please choose one of the options")
            main()

TwoDShapeMenu.py

import math
import MainProgram

previousfunction = ""

def twodshapes():
        answer = input("Enter the number of the shape area you want to calculate: \n 1.Triangle \n 2.Trapezium \n 3.Square \n 4.Rectangle \n 5.Parallelogram \n 6.Rhombus/Kite/Diamond \n 7.Circle \n 8.Oval \n")
        answer = answer.upper()
#It then follows through all the options, then I created another function that returns me to the main menu of the main file.

def postdecision(previousfunction):
    print("Input 1 if you would like to calculate the area/perimeter of this shape again")
    print("Input 2 if you would like to return to the 2D shape menu")
    print("Input 3 if you would like to return to the main menu")
    print("Input 4 if you would like to exit the program")
    answer = input()

    #Option 3 looks like this

    if answer == "3":
        MainProgram.main()

我期望文件导入没有任何问题,但是没有,相反,它给了我一个属性错误:

AttributeError:模块'TwoDShapeMenu'没有属性'twodshapes'

2 个答案:

答案 0 :(得分:0)

我解决了这个问题。在我创建的每个菜单文件中,我都定义了一个仅在需要时才将主菜单导入文件的函数(并且在导入主菜单时,它将临时存储在CPU缓存中,直到代码停止,因此每次该函数被从我读过的内容来看,整个操作要快得多),然后在主文件中创建了一个指向所有文件的菜单,我将其他项目导入到顶部,没有任何问题。

我的问题是我将主菜单文件导入到项目顶部的其他文件中,这导致了循环导入,这在python中从来都不是好事。

答案 1 :(得分:-1)

我只是复制/粘贴您的代码,它的工作没有问题...

C:\Users\User>F:\asdfasdf\MainProgram.py
Please choose something from the list below:
 1.Area/Perimeter of 2D Shapes
 2.Volume/Surface area of 3D Shapes

1
Enter the number of the shape area you want to calculate:
 1.Triangle
 2.Trapezium
 3.Square
 4.Rectangle
 5.Parallelogram
 6.Rhombus/Kite/Diamond
 7.Circle
 8.Oval

也许再次检查您的文件夹结构或任何错字?

相关问题