**:
1、類屬於模組的一部分。當我們要建立乙個類時,通常我們新建乙個py檔案,例如新建立cn.py,這個cn便成為我們的模組。
2、然後在cn裡面建立自己的類:
python**
'''''created on 2011-11-1
@author: dudong0726
'''class person:
'''''
classdocs
'''count = 0
def __init__(self,name,age):
'''''
constructor
@param: name the name of this person
@param: age the age of this person
'''self.name = name
self.age = age
person.count += 1
def detail(self):
'''''
the detail infomation of this person
'''print('name is ',self.name)
print('age is ',self.age)
print('there are '+str(person.count)+" person in the class")
3、我們需要在另乙個模組中使用這個類,有兩種匯入方式
1)from cn import * 也就是從cn模組中把所有的東西都匯入進來
python**
'''''created on 2011-11-1
@author: dudong0726
'''from cn import *
if __name__ == '__main__':
p = person('marry',21)
p.detail()
q = person('kevin',24)
q.detail()
2)import cn 告訴python我們將要使用這個模組的東西,當我們使用時要在前面加上cn.來指明來自cn這個模組
python**
'''''
created on 2011-11-1
@author: dudong0726
'''import cn
if __name__ == '__main__':
p = cn.person('marry',21)
p.detail()
q = cn.person('kevin',24)
q.detail()
4、我們可以在cn模組中建立乙個函式
python**
'''''
created on 2011-11-1
@author: dudong0726
'''def say(word):
print(word)
class person:
'''''
classdocs
'''count = 0
def __init__(self,name,age):
'''''
constructor
@param: name the name of this person
@param: age the age of this person
'''self.name = name
self.age = age
person.count += 1
def detail(self):
'''''
the detail infomation of this person
'''print('name is ',self.name)
print('age is ',self.age)
print('there are '+str(person.count)+" person in the class")
5、在另外的模組中呼叫這個函式
你可以這樣呼叫:
python**
'''''
created on 2011-11-1
@author: dudong0726
'''from cn import *
if __name__ == '__main__':
p = person('marry',21)
p.detail()
q = person('kevin',24)
q.detail()
say("hello world")
當然也可以這樣:
python**
'''''
created on 2011-11-1
@author: dudong0726
'''import cn
if __name__ == '__main__':
p = cn.person('marry',21)
p.detail()
q = cn.person('kevin',24)
q.detail()
cn.say("hello world")
零基礎學Python(第十七章 模組import)
在前面的幾個章節中我們指令碼上是用 python 直譯器來程式設計,如果你從 python 直譯器退出再進入,那麼你定義的所有的方法和變數就都消失了。為此 python 提供了乙個辦法,把這些定義存放在檔案中,為一些指令碼或者互動式的直譯器例項使用,這個檔案被稱為模組。模組是乙個包含所有你定義的函式...
python學習筆記3 模組和類
模組屬性和變數的檢視 dir 變數刪除 del x 模組reload import importlib importlib.reload model 模組是包含一定功能實現的集合,一般標準庫和安裝的模組儲存在 python lib或 python lib site packages 引入的模組可以對...
python類 模組 包
通常包總是乙個目錄,可以使用import匯入包,或者from import來匯入包中的部分模組。包目錄下為首的乙個檔案便是 init py。然後是一些模組檔案和子目錄,假如子目錄中也有 init py 那麼它就是這個包的子包了。在建立許許多多模組後,我們可能希望將某些功能相近的檔案組織在同一資料夾下...