Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-带超级函数调用方法的循环导入_Python_Class_Import_Circular Dependency_Super - Fatal编程技术网

Python-带超级函数调用方法的循环导入

Python-带超级函数调用方法的循环导入,python,class,import,circular-dependency,super,Python,Class,Import,Circular Dependency,Super,我有两个文件。代码之间似乎存在循环导入。我怎样才能解决它?我必须使用超级函数来调用第一个文件中的函数 report.py import report_y as rpt from aldjango.report import BaseReport class Report(BaseReport): def gen_x(self): output = rpt.Ydetail(*args) .... #code that generate a

我有两个文件。代码之间似乎存在循环导入。我怎样才能解决它?我必须使用超级函数来调用第一个文件中的函数

report.py

import report_y as rpt
from aldjango.report import BaseReport

class Report(BaseReport):
    def gen_x(self):
        output = rpt.Ydetail(*args)
        ....
        #code that generate a PDF report for category X

class HighDetail(object):
    def __init__(self, *args, **kwargs):
        ....   
     #functions that generate output
报告y.py

from report import HighDetail
class YDetail(HighDetail):
    #do something override some argument in HighDetail method
    new_args = orginal args + new args
    super(YDetail, self).__init__(*new_args, **kwargs)
Python中没有“循环导入”问题。导入已导入的模块将被悄悄忽略。任何初始化代码将仅在第一次导入模块时运行


即使给模块一个带有import…as的别名,这也是正确的。

我编写了一个更简洁的示例来重现您的问题:

a、 派克

导入b
A类(对象):
def从_b(自身)获取_魔法_编号_:
返回b.magic_number()
b、 派克

导入一个
def magic_number():
返回42
B类(a.a):
通过
与您的示例类似,模块B中的类B继承自模块A中的类A。同时,类A需要模块b提供一些功能来执行其功能(通常,如果可以,您应该尽量避免这种情况)。现在,当您导入模块a时,Python也将导入模块b。由于类b.b显式依赖于a.a,在执行
import b
语句时尚未定义a.a,因此此操作失败,出现
AttributeError
异常

要解决此问题,您可以将
import b
语句移到A的定义后面,如下所示:

class A(object):

  def get_magic_number_from_b(self):
    return b.magic_number()

import b
class A(object):

  def get_magic_number_from_b(self):
    import b
    return b.magic_number()
,或者将其移动到依赖于模块b的功能的函数定义中,如下所示:

class A(object):

  def get_magic_number_from_b(self):
    return b.magic_number()

import b
class A(object):

  def get_magic_number_from_b(self):
    import b
    return b.magic_number()

或者,您可以确保始终在模块
a
之前导入模块
b
,这也将解决问题(因为a对b没有导入时间依赖关系)。

解决问题的另一种方法是将类
HighDetail
移动到
report_y.py
中,它看起来像第一个文件,
report.py
正在导入自身--我认为这是实际问题。抱歉,这是个错误