您的位置:首页 > 编程语言 > Python开发

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

2018-02-07 14:27 435 查看
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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: