python 2.7 : 引用模块时出现TypeError:'module' object is not callable

本文介绍了Python中如何正确地导入并使用自定义模块。通过一个具体的例子解释了常见错误TypeError: 'module' object is not callable的原因及解决办法,并提供了三种正确的模块调用方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Student.py文件:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

'Student module'

__author__ = 'afei'


class Student(object):
    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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值