【再回首Python之美】【模块】使用module

python自带了功能非富多彩的标准库,以及还有很多第三方库。

使用这些功能的基本方法:使用模块

可使用对象:模块中的变量和函数,由模块.py或者.pyc文件提供

模块存在形式:.py或者.pyc文件,一般在C:\Python27\Lib目录下

效率:通过使用python自带模块的函数或者变量,可以重用其代码,从而提高自己代码工作量,甚至代码性能


示例代码:

#ex_template.py by oneself
self_file = __file__#current file path

print "\nShow function and variable in random module=========="
import random       #Tell python, use random module
print dir(random)   #With the help of dir()
#会输出如下list
#['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random',
# 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill',
#'_BuiltinMethodType', '_MethodType', '__all__', '__builtins__',
#'__doc__', '__file__', '__name__', '__package__', '_acos',
#'_ceil', '_cos', '_e', '_exp', '_hashlib', '_hexlify',
#'_inst', '_log', '_pi', '_random', '_sin', '_sqrt',
#'_test', '_test_generator', '_urandom', '_warn',
#'betavariate', 'choice', 'division', 'expovariate',
#'gammavariate', 'gauss', 'getrandbits', 'getstate',
#'jumpahead', 'lognormvariate', 'normalvariate',
#'paretovariate', 'randint', 'random', 'randrange',
#'sample', 'seed', 'setstate', 'shuffle', 'triangular',
#'uniform', 'vonmisesvariate', 'weibullvariate']

print "\nUse function in random module======"
from random import randint  #Use randint function in random module
print randint(0,10)         #Return random integer in range [0, 10], including both end points.
print random.randint(0,10)  #be equivalent to above two line code

print "\nUse variable in random module======"
from random import __file__ #Use __file__ variable in random module
print __file__              #C:\Python27\lib\random.pyc
print random.__file__       #be equivalent to above two line code

print "\nAlias for variable in random module======"
from random import __file__ as random_file
print random_file           #C:\Python27\lib\random.pyc   

print "\nAlias for function in random module======"
from random import randint as random_randint
print random_randint(0,10)

print "\nexit." + self_file
编译执行:


(end)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值