在一個文件中引用另外一個文件中的類

程序代碼 
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 html

 

 

=============下面這個解法更能體現問題所在,就是模塊的路徑問題 shell

問題: 函數

       
    我不能肯定我爲何獲得這個錯誤: ui

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

源代碼以下: url

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

答覆: spa

 

"TypeError: 'module' object is not callable"這個信息是說你試圖把"urlparse"這個模塊做爲一個函數來調用,但它卻沒法調用。 htm

 

urlparse這個模塊包含urlparse 和 urlsplit等函數。我把urlsplit也拖了進來,它的名字和模塊名不一樣。這個可能能幫助你發現問題。如下是調用它們的兩種方法。 it

 

(1) ast

  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) class

  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可能更適合你。

相關文章
相關標籤/搜索