Student.py文件:
#!/usr/bin/env python# -*- coding: utf-8 -*-
'Student module'
__author__ = 'afei'
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print "%s : %d" % (self.name, self.score)
引用模块:
import Student
st = Student('afei', 99)
st.print_score()
运行时出现 TypeError:'module' object is not callable
原因是Python引用模块方式有两种:
import module 使用时需加上模块名的限定
from module import * 直接使用没有限定
修改上述引用:
import Student
st = Student.Student('afei', 99)
st.print_score()
或者
from Student import *
st = Student('afei', 99)
st.print_score()
或者
from Student import Student
st = Student('afei', 99)
st.print_score()
本文介绍了Python中如何正确地导入并使用自定义模块。通过一个具体的例子解释了常见错误TypeError: 'module' object is not callable的原因及解决办法,并提供了三种正确的模块调用方式。

1万+

被折叠的 条评论
为什么被折叠?



