首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python模块和类在import下的区别

2012-10-17 
python模块和类在import上的区别1、类属于模块的一部分。当我们要建立一个类时,通常我们新建一个py文件,例如

python模块和类在import上的区别

1、类属于模块的一部分。当我们要建立一个类时,通常我们新建一个py文件,例如新建立cn.py,这个cn便成为我们的模块。

2、然后在cn里面建立自己的类:

'''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模块中把所有的东西都导入进来

?

'''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这个模块

?

'''Created on 2011-11-1@author: dudong0726'''import cnif __name__ == '__main__':    p = cn.Person('marry',21)    p.detail()    q = cn.Person('kevin',24)    q.detail()
?

4、我们可以在cn模块中建立一个函数

?

'''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、在另外的模块中调用这个函数

? 你可以这样调用:

?

'''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")
?

?

? ? 当然也可以这样:

'''Created on 2011-11-1@author: dudong0726'''import cnif __name__ == '__main__':    p = cn.Person('marry',21)    p.detail()    q = cn.Person('kevin',24)    q.detail()        cn.say("hello world")

热点排行