模块交叉参考设计问题

时间:2016-09-16 17:48:30

标签: python python-2.7

我有一个名为testlib.py的python文件,其意图定义了其他模块使用的一些实用程序类和全局函数。 uselib.py被设计为使用testlib.py中的类/全局函数的客户端。

由于某些设计问题,testlib.py需要引用Goo中定义的某个类uselib.py。如果我只是直接导入,则会出现错误消息(如下所示)。

只是想知道如何在Python 2.7中优雅地处理这种情况以进行交叉引用

uselib.py

import testlib

class Goo:
    def __init__(self):
        pass
    def checkValue(self):
        return "check value in Goo"

print testlib.globalFoo()
f = testlib.Foo()
print f.getValue()

testlib.py

import uselib

class Foo:
    def __init__(self):
        pass
    def getValue(self):
        g = uselib.Goo()
        g.checkValue()
        return 'get value in class Foo'

def globalFoo():
    return 'in global foo'

错误消息

Traceback (most recent call last):
  File "/Users/foo/personal/uselib.py", line 1, in <module>
    import testlib
  File "/Users/foo/personal/testlib.py", line 1, in <module>
    import uselib
  File "/Users/foo/personal/uselib.py", line 9, in <module>
    print testlib.globalFoo()
AttributeError: 'module' object has no attribute 'globalFoo'

1 个答案:

答案 0 :(得分:1)

我想出了一个鬼鬼祟祟的黑客攻击:当你在import testlib调用__main__函数时,只能uselib.py。在这种情况下,使用if __name__ == "__main__"中的uselib.py检查很重要。这样,您就可以避免循环导入。 testlib.py包含uselib.py中的所有类,但uselib.py仅在需要调用它们时加载testlib.py中的所有内容。

uselib.py 的代码:

#import testlib

class Goo:
    def __init__(self):
        pass
    def checkValue(self):
        return "check value in Goo"

if __name__ == "__main__":
    import testlib
    print testlib.globalFoo()
    f = testlib.Foo()
    print f.getValue()

testlib.py 的代码:

import uselib

class Foo:
    def __init__(self):
        pass
    def getValue(self):
        g = uselib.Goo()
        g.checkValue()
        return 'get value in class Foo'

def globalFoo():
    return 'in global foo'

输出:

Chip chip@ 04:00:00@ ~: python uselib.py
in global foo
get value in class Foo

请注意:import testlib中的任何仲裁函数也可以调用uselib.py,它不需要__main__。 E.g:

另一个 uselib.py 的代码:

#import testlib

class Goo:
    def __init__(self):
        pass
    def checkValue(self):
        return "check value in Goo"
def moretest():
   import testlib
   print testlib.globalFoo()
   f = testlib.Foo()
   print f.getValue()

#if __name__ == "__main__":
    #import testlib
    #print testlib.globalFoo()
    #f = testlib.Foo()
    #print f.getValue()

stackoverflow.py 的代码:

import uselib
uselib.moretest()

调用 stackoverflow.py

Chip chip@ 04:30:06@ ~: python stackoverflow.py
in global foo
get value in class Foo