Python属性错误
我有三个Python文件:
one.py
、two.py
和three.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()
?
______________edit________________V
我可以这样调用它:
two().three()
def two():
import three as three
return three
但我想这样调用:
two.three()
所以基本上它会自动执行def two():
2 个回答
0
当你调用一个模块时,这个被调用的模块自己无法检查它是否有某个函数。如果没有这个函数,它也不知道该怎么处理。你可以把两次调用的代码放在一个“尝试-捕获”的结构里,这样如果出现找不到函数的错误,就能处理这个错误。
try:
two.three()
except AttributeError:
three.three()
1
这是我想到的解决方案。我承认,是因为你的问题让我想要搞明白这个,所以我自己也不是完全理解。这里的关键在于文件two.py,在这里尝试访问并调用two的three
方法时,是通过method_router
__getattr__方法来处理的。这个方法使用__import__
根据名字(字符串)导入指定的模块,然后通过再次调用getattr()
来模拟from blah import blah
的效果。
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")