python模块和类在import上的区别

转载自:http://dudong0726.iteye.com/blog/1226907

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 cn

if __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 cn

if __name__ == '__main__':
    p = cn.Person('marry',21)
    p.detail()
    q = cn.Person('kevin',24)
    q.detail()
    
    cn.say("hello world")


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值