2013-01-24 75 views
0

我有三个Python文件蟒蛇AttributeError的

one.pytwo.pythree.py

one.py

one.py我打电话

import two as two 
    two.three() 

two.py

def two(): 
    "catch the error here then import and call three()" 
    import three as three 
three.py

def three(): 
    print "three called" 

所以很自然我越来越:

AttributeError: 'function' object has no attribute 'three'

我的问题是:

有没有办法有two.py捕获错误然后导入three.py和然后致电three()

__ _ __ _ __ _ __ _ __编辑_ __ _ __ _ __ _ __ _ __ _V
我可以这样调用:

two().three() 

def two(): 
    import three as three 
    return three 

但我想叫它像这样:

two.three() 

所以基本上它会自动EXEC高清两():

+3

你能解释一下你想要什么来实现(在更广泛的层面)? –

+0

假设你的意思是说'从两个进口的两个'和'从三个进口的三个'来代替我会是正确的吗? – neirbowj

+0

我正在尝试创建一个可以调用的全局对象。 所以导入会发生,然后导入后功能将可用。 – Natdrip

回答

1

这是我提出的解决方案。我承认,我受到你的问题的启发,试图弄清楚这一点,所以我自己并没有完全理解它。神奇的事情发生在two.py,其中尝试访问然后调用的three方法由method_router类的__getattr__方法处理。它使用__import__按名称(字符串)导入指示的模块,然后通过在导入的模块上再次调用getattr()来模仿from blah import blah

one.py

from two import two 
two.three() 

两项。PY

class method_router(object): 
    def __getattr__(self, name): 
     mod = __import__(name) 
     return getattr(mod, name) 

two = method_router() 

three.py

def three(): 
    print("three called") 
+0

我想我可以用这个答案。我会告诉你。 Thx – Natdrip

+0

我想这样做:two.three()但不会工作它会像这样工作()。三() def two():import three as three return three – Natdrip

0

当你调用模块时,被调用的模块无法自行检查它是否具有函数,并且如果不遵循替代路径。你可以包装two.three()来尝试except子句来捕获属性错误。

try: 
    two.three() 
except AttributeError: 
    three.three()