我有一个名为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'
答案 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