Python继承导入模块时出现Traceback错误,请求解决
解决Python 2.7中类继承模块导致的TypeError问题
这个错误的核心原因很明确:你在third.py里试图继承模块对象,而不是模块里的类。
看你的代码,import first导入的是整个first.py模块,而不是模块里名为first的类;import second同理。当你写class third (first, second):时,Python会把first和second当成父类,但它们其实是模块,这就触发了TypeError——模块不能作为类的基类。
修正步骤
1. 修正导入语句,精准导入类
把third.py里的导入改成直接导入模块中的类:
from first import first from second import second class third(first, second): def fun3(self): f = first() s = second() f.fun1() s.fun2() print 'third one'
2. 修复类方法的参数问题
另外还要注意:你原来的fun1、fun2、fun3都没有加self参数。在Python中,实例方法必须把self作为第一个参数(代表实例本身),否则创建实例调用方法时会报错。所以需要同步修改另外两个文件:
first.py:
class first(): def fun1(self): print 'first one'
second.py:
class second(): def fun2(self): print 'second one'
如果你的方法不需要访问实例属性,也可以用@staticmethod装饰器把它们变成静态方法,这样就不需要self参数,比如:
class first(): @staticmethod def fun1(): print 'first one'
验证修复效果
现在运行third.py,如果要测试fun3,可以在文件末尾加上:
if __name__ == '__main__': t = third() t.fun3()
执行后就能正常输出:
first one second one third one
内容的提问来源于stack exchange,提问作者Ajay
相关产品推荐
相关产品推荐

