0

我有三个 python 文件

one.py, two.py,three.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:“函数”对象没有属性“三”

我的问题是:

有没有办法two.py捕获错误然后导入three.py然后调用three()

__ _ __ _ __ _ __ _ __编辑_ __ _ __ _ __ _ __ _ __ _V
我可以这样称呼它:

two().three()

def two():
    import three as three
    return three

但我想这样称呼它:

two.three()

所以本质上它会自动执行 def two():

4

2 回答 2

1

Here's the solution I came up with. I confess that I was inspired by your question to try to figure this out, so I don't completely understand it myself. The magic happens in two.py where the attempt to access and then call the three method of two is handled by the __getattr__ method of the method_router class. It uses __import__ to import the indicated module by name (a string), and then imitates the from blah import blah by calling getattr() again on the imported module.

one.py

from two import two
two.three()

two.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")
于 2013-01-25T00:00:13.640 回答
0

当您调用一个模块时,被调用的模块无法自行检查它是否具有功能,如果没有则遵循替代路径。您可以将 two.three() 包裹在 try except 子句中以捕获属性错误。

try:
   two.three()
except AttributeError:
   three.three()
于 2013-01-24T23:59:20.573 回答