当前位置

Python 的一个 TypeError: unbound method ... 问题

碰到这个问题的时候,网上找到最接近的案例是 http://mail.python.org/pipermail/python-list/2002-July/154968.html, 可惜没有下文。后来在 http://www.nabble.com/TypeError-in-base-class-__init__-after-reload-td15058502.html 的帮助下找到了原因。

不太好描述,写具体例子吧,一共需要三个 py 文件:
module1.py

  1. class Super:
  2.     def __init__(self):
  3.         pass

module2.py

  1. import module1
  2.  
  3. class Sub(module1.Super):
  4.     def __init__(self):
  5.         module1.Super.__init__(self)

run.py

  1. from imp import load_source
  2.  
  3. x = load_source("module2", "module2.py")
  4. #load_source("module1", "module1.py")
  5. print x.Sub()

这三个文件放在同一个目录下,然后运行 run.py,结果看起来很好;但如果我们去掉 run.py 里面的那个注释,就得到错误:
TypeError: unbound method __init__() must be called with Super instance as first argument (got Sub instance instead)

用人家的解释就是:there are some real problems with reloading modules when you have references to objects in the module object. The module is reloaded but the references are not automatically rebound to the new module.

当应用需要从一个目录下 import 所有的模块的时候,如果忘了这个依赖问题,就可能出错了;而且这个错误和遍历目录获得的文件顺序有关,有可能在开发环境下好好的,但部署到生产系统后问题才暴露。切记切记

Topic: