【Python】TypeError: 'module' object is not callable 原因分析

 程序代码
class Person:
     #constructor
     def __init__(self,name,sex):
          self.Name = name
          self.Sex = sex
     def ToString(self):
          return 'Name:'+self.Name+',Sex:'+self.Sex
在IDLE中报错:
>>> import Person
>>> per = Person('dnawo','man')
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    per = Person('dnawo','man')
TypeError: 'module' object is not callable
原因分析:
Python导入模块的方法有两种:import module 和 from module import,区别是前者所有导入的东西使用时需加上模块名的限定,而后者不要。
正确的代码:
>>> import Person
>>> person = Person.Person('dnawo','man')
>>> print person.Name

>>> from Person import *
>>> person = Person('dnawo','man')
>>> print person.Name

 

 

=============下面这个解法更能体现问题所在,就是模块的路径问题

问题:

      
    我不能确定我为什么得到这个错误:

  1. ************************************************** **************
  2. Traceback (most recent call last):
  3. File  "my.py" , line  3in  ?
  4. urlparse( 'http://www.cwi.nl:80/%7Eguido/Python.html')
  5. TypeError:  'module'  object is   not  callable
  6. ************************************************** 

源代码如下:

  1. import  urlparse
  2. urlparse( 'http://www.cwi.nl:80/%7Eguido/Python.html')

答复:

 

"TypeError: 'module' object is not callable"这个信息是说你试图把"urlparse"这个模块作为一个函数来调用,但它却无法调用。

 

urlparse这个模块包含urlparse 和 urlsplit等函数。我把urlsplit也拖了进来,它的名字和模块名不同。这个可能能帮助你发现问题。以下是调用它们的两种方法。

 

(1)

  1. >>>  import  urlparse
  2. >>> urlparse.urlparse( 'http://www.cwi.nl:80/%7Eguido/Python.html')
  3. ( 'http' 'www.cwi.nl:80''/%7Eguido/Python.html''''''' )
  4. >>> urlparse.urlsplit( 'http://www.cwi.nl:80/%7Eguido/Python.html')
  5. ( 'http' 'www.cwi.nl:80''/%7Eguido/Python.html''''' )
  6. >>>

 

(2)

  1. >>>  from  urlparse  import  urlparse, urlsplit
  2. >>> urlparse( 'http://www.cwi.nl:80/%7Eguido/Python.html')
  3. ( 'http' 'www.cwi.nl:80''/%7Eguido/Python.html''''''' )
  4. >>> urlsplit( 'http://www.cwi.nl:80/%7Eguido/Python.html')
  5. ( 'http' 'www.cwi.nl:80''/%7Eguido/Python.html''''' )
  6. >>>

方法1可能更适合你。

 

  • 10
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值