如何将函数的结果从一个文件传递到另一个文件

How to pass the results of a function from one file to another file

当我在主文件(命名为 INPUT.py)中打印一个函数的结果时出现错误。这些函数在另一个文件中创建(命名为 ENGINE.py)。错误是:AttributeError: module 'ENGINE' has no attribute 'cross_section' 我不明白为什么会出现这样的错误。

这里是代码示例:

#-- 主文件:INPUT.py

class Duct:
    def __init__(self, width, height):
        self.width = width 
        self.height = height 
    
Duct_ret = Duct(0.1, 0.1)

Duct_ret.width= 0.4
Duct_ret.height= 0.3

import ENGINE as EN
print(EN.cross_section)

#-- 引擎文件:ENGINE.py

from INPUT import width, height

def cross_section(self,):
    c_s=height*width
    return c_s 

错误:AttributeError:模块 'ENGINE' 没有属性 'cross_section'

发生这种情况是因为您的代码中存在循环依赖。

ENGINE.py 中导入 heightwidth,在 INPUT.py 中导入 ENGINE.

您应该将 Duct_ret.heightDuct_ret.width 传递给辅助函数而不是导入它们。

所以不是这个:

import ENGINE as EN
print(EN.cross_section)

这样做:

import ENGINE as EN
print(EN.cross_section(Duct_ret.height, Duct_ret.width))

并在 ENGINE.py 中定义如下函数:

def cross_section(height, width):
    c_s = height * width
    return c_s

注意:您还使用 self 作为 cross_section 的参数,这是不正确的,因为 cross_section 不是 class 方法——您只需要将相关参数传递给函数(您的原始代码没有)。

旁注:在这种情况下,您应该将 import 移动到 INPUT.py 中文件的开头以获得更好的样式。

@costaparas 回答的很详细

我还尝试了给定的代码来找到解决方案。在尝试解决这个问题时,我发现您的代码有 2 个问题:

  1. 您不应该使用 import 在不同的文件中获取 class 变量。
  2. 您在两个文件中都使用了顶级导入,这导致了错误的循环依赖。

解决方案:

INPUT1.py

class Duct:
    def __init__(self, width, height):
        self.width = width 
        self.height = height 
    
Duct_ret = Duct(0.1, 0.1)

Duct_ret.width= 0.4
Duct_ret.height= 0.3

from ENGINE import cross_section1 as cs
cs(Duct_ret.width, Duct_ret.height)

ENGINE.py

def cross_section1(width,height):
    c_s=height*width
    print (c_s)