python模組和類在import上的區別
阿新 • • 發佈:2019-01-03
轉自:http://dudong0726.iteye.com/blog/1226907
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")