Python notes the 3rd Chapter, modules and modules of common methods, functional programming yield, ternary operation lambda expression, built-in culvert number, common modules

Source: Internet
Author: User
Tags chop ord pow vars

<--Directory--

    • Common methods for modules and modules

    • Function-Type programming

    • Yield

    • Ternary operations

    • Lambda expression

    • Built-in Culvert number

    • Common modules



"Common methods for modules and modules"
The critical __init__.py #包一定要有这个__init__. py file, he is the package, in order to use the form Package name Import module name (. py file name) to refer to a module of this package function function

Determine if the main file: __name__
if __name__ = = ' __main__ '

Current file path: __file__

Current File Description: __doc__


1) If __name__ = = ' __main__ '
Example 1:
Under Main's package, there is an index module
Under file's package, there is a demo module

Cat index.py#!/usr/bin/env python#coding:utf-8print __name__python index.pyprint __main__cat demo.py#!/usr/bin/env Python#coding:utf-8print __name__python demo.pyprint __main__ example 2:cat index.py#!/usr/bin/env python#coding:utf-8from        File import demoprint ' index ', __name__cat demo.py#!/usr/bin/env python#coding:utf-8print ' demo ', __name__def Foo (): Print "Old dog to chop wood" python index.pydemo,file.demoindex,__main__

Summary: via if __name__ = = ' __main__ ':
To judge the current. Py script is not the main program, if it is the main program execution, the advantage is when hackers come to attack, to call my main program he does not call on

2) Current file path: __file__
3) Current file description: __doc__

Example:

[[email protected] opt]# pwd;ls/opt/test.pycat test.py#!/usr/bin/env python#coding:utf-8 ' ' This is G test@author:wsyht ‘‘‘

4) Print __file__ #查看当前文径路径
5) Note for print __doc__ #查看模块 (. py file)

[email protected] opt]# python test.py test.pythis is g [email protected]:wsyht



"Functional Programming"
Parametric def Fun (Arg,*args,**kargs):
Default parameter Print arg
Variable-parameter print args
Print Kargs
Returns the value return ' success '


1) Example of default parameters and return values
Example 1:

def foo (name):p rint name, ' Go Firewood ' foo (' Wsyht ') foo (' Jenkins ') foo (' Peter ')


Example 2:

DEF login (username): if username = = "Wsyht": Return ' login successful ' Else:return ' login failed ' def detail (user):p rint user, ' verify success ' if __name__ = = ' __main__ ': user= raw_input (' Please enter username: ') res = login (user) #检查用户是否登陆成功if res = = "Login Successful" detail (user) #显示详细信息else:p rint "no bonus The


Example 3:

def foo (name,action= ' firewood ', where= '): Set default = Cut wood, you can add multiple default parameters, but the default parameter must be placed in the last print name, ' Go ', Action,wherefoo (' wsyht ', ' Chop wood ') Foo (' Jenkins ', ' eat ') #不设置第二个值, will use set the default parameters of "Wood" foo (' Peter ', Where= ' Shanghai ') #默认按位置传参, designate where= ' Shanghai ', that is, can not be passed in order, to his value is Shanghai, Regardless of where in the above location foo (' Jim ', Where= ' Shanghai ', action= "oo") #默认按位置传参, the designation where= ' Shanghai ', that is, can not be transmitted in sequence, give him the value of Shanghai, regardless of where the location of the above where


2) Examples of variable parameters
Example 4:

#!/usr/bin/env python#coding:utf-8 "Def show1 (ARG):         for item in arg:                 print itemdef show2 (ARG1,ARG2):         print arg1,arg2         #show1 ([' Lyang ', ' wsyht ']) show2 (' Liyang ', ' Zhangsan ') def show (*arg):    #加一个 * You can add n parameters     for item in  arg:            print itemshow (' Wsyht ', ' Tom ', ' Peter ', ' Jenkins ', ' Jack ') '     ' Def show (**kargs):        for item in kargs.items ():             print item            show ( Name= ' Wsyht ', age= ' 26 ') '"#以元组方式传进去def  show (**kargs):        for item in  Kargs.items ():            print item   user_dict={' K1 ': 123, ' K2 ': 456}show (**user_dict)    #元组方式传进去前面要加两个 *


"Use of yield"
code Example 1:

#!/usr/bin/env python#coding:utf-8 "Print range" Print xrange (Ten) for item in Xrange: #便 profit generates digital print item '  def foo (): Yield 1 #eclipse上打上断点, debug test yield 2 yield 3 yield 4 yield 5re = foo () #print re #调用的是生成器for Item in Re: #便利的时候才能使用re print item


code Example 2:

#!/usr/bin/env python#coding:utf-8def wsyhtreadlines ():     seek = 0     while true:        with open (' F:/ Wsyht.txt ', ' R ')  as f:            f.seek ( Seek)             data = f.readline ()    #读取一行             if data:                 seek =  F.tell ()                 yield  data            else:                 return  #如果return了, then the entire function exits #print  wsyhtreadlines () &nbSP; #这样输出就是一个生成器for  item in wsyhtreadlines ():         Print item ' F = open (' D:/temp.txt, ' R ') F.read () F.close () with open (' D:/temp.txt ', ' R ')   as f:   #这样写就不需要再对文件close了     print  ' xxxx ' print  ' OK '


"Ternary operations and lambda expressions"
1) Ternary operation
code example:

result = ' GT ' If 1>3 Else ' LT ' Print result example: #!/usr/bin/env python#coding:utf-8temp = noneif 1>3:temp = ' GT ' else:temp = ' LT ' Print temp# The above method implements the same result as the following code method result = ' GT ' If 1>3 Else ' LT ' Print result


2) lambda expression
code example:

A = Lambda x,y:x+yprint A (4,10)


Example:

#!/usr/bin/env pythondef foo (x, y): Return x+yprint foo (16,10) temp = Lambda X,y:x+yprint temp (16,10) ' temp = lambda x:x *xprint Temp (4) "" temp = lambda x,y,z:x+y+zprint temp (1,3,5) "Other example:>>> [i*2 for I in range (10)] [0, 2, 4, 6,  8, 18]f>>> Map (lambda x:x*2, Range) [0, 2, 4, 6, 8, ten, +, +, 18]>>> map (lambda X:x**x, Range (Ten)) [1, 1, 4, 3125, 46656, 823543, 16777216, 387420489]>>>



"Built-in functions"
Help () #查看帮助
Dir () #把相应的key列出来, all built-in functions
VARs () #列出所有key和Values, all built-in functions
Type () #查看类型
Import Temp #导入模块
Reload (temp) #重复导入模块
ID () #查看内存地址

#help, dir (), VARs (), type () demo

>>> a = [] #它是一个类, call a class to create a Class table >>> a1 = list () >>> Help (a) #查看帮助 >>> print dir () #把相应的key列出来, all built-in functions >>> print VARs () #列出所有key和Values, all built-in functions >>> print type (a) #查看类型 >>> prin T type (A1) #查看类型


#reload (Demo) Demo
#file包下有一个demo. py Module Files
#main包下有一个index. py file

#cat demo.py#!/usr/bin/env python#coding:utf-8print ' demo.py ' #python index.py#python index.py#!/usr/bin/env python# Coding:utf-8from File Import Demo #当导入的时候就会执行一篇demo模块里面的所有代码 #from file Import demo #Python下再用重复的代码导入相同的模块是不会导入的, he only imports once #如果想导两次, you need to use Reload (demo) from file Import Demoreload (demo)


#id演示 to see the amount of memory space occupied

>>> t1=123>>> t2=888>>> Print ID (t1) 28244048>>> print ID (T2) 28560048


CMP () to determine the value before and after the size of the former large-1, after the big 1, the same big 0
ABS () to find the value of sleep
BOOL () 0 is false, other is true
Divmod () to seek the remainder of the business
Man () to find the maximum value
Min () to find the minimum value
SUM () sum
POW () Seek the second party

>>> cmp (2,3) #后面大负1 -1>>> cmp (5,3) #前面大正11 >>> cmp (5,5) #等大出零0 >>> Print ABS (-9) #求觉对值9 >>> print bool (0) #求布尔值False >>> print bool (1) true>>> print bool (true>>>) print bool ( -3) true>>> print divmod (9,4) #求商取余 (2, 1) >>> print Divmod (14,4) (3, 2) >>> print DIVM OD (15,3) (5, 0) >>> print max ([11,22,33,333]) #求最大值333 >>> print min ([11,22,33,333]) #求最小值11 >> > Print sum ([11,22,33]) #求和66 >>> print pow (2,3) #2的3次方8


All () a fake is true
Any () It's true, it's all fake.

>>> Print all ([1,2,3,0]) #一假则假False >>> Print All ([1,2,3,1]) #全真则真True >>> Print any ([0,0,0,0 ]) #全假则假False >>> Print any ([1,0,0,0]) #一真则真True >>> Print any ([1,2,3,1]) true>>> print bool (' ') false>>> print bool (None) False


Ord () number corresponding to Ascall code
Hex () 16 binary conversion
Oct () octal conversion
Bin () binary conversion

>>> print CHR #ASCALL码对应的字符A >>> print CHR b>>> print chr (c>>>) Print Chr ( d>>> print Chr (e>>>) Print ord (' A ') #ASCALL码对应的数字65 >>> print ord (' B ') 66>>> Print Hex #十六进制转换0x7d0 >>> print Oct #八进制转换03720 >>> Print bin (2) #二进制转换0b10


Enumerate () plus serial number
Format () formatted output

>>> li = [' watch ', ' car ', ' room '] >>> for item in li:print  item...  Watch Car room >>> for item in enumerate (LI):p rint item     #enumerate是加序列号 ...  (0,  ' \xe6\x89\x8b\xe8\xa1\xa8 ') (1,  ' \xe6\xb1\xbd\xe8\xbd\xa6 ') (2,   ' \XE6\X88\XBF ') >>> for item in enumerate (li,1):p rint item     #括号第二个参数是指起始值 ...  (1,  ' \xe6\x89\x8b\xe8\xa1\xa8 ') (2,  ' \xe6\xb1\xbd\xe8\xbd\xa6 ') (3,  ') \XE6\X88\XBF ') >>> for item in enumerate (li,3):p rint item ...  (3,   ' \xe6\x89\x8b\xe8\xa1\xa8 ') (4,  ' \xe6\xb1\xbd\xe8\xbd\xa6 ') (5,  ' \XE6\X88\XBF ') >>>  for item in enumerate (li,1):p rint item[0],item[1]... 1  watch 2  car 3  room >>> s= ' My name {0} {1} '          > >> print s. Format (' is ', ' wsyht ') my name is wsyht>>> s= ' my name {0},{1} '           >>> print s.format (' is ', ' wsyht ') My  Name is,wsyht


#调用函数的两种方法

def function (ARG): Print arg function (' Wsyht ') #第一种调用方法apply (function, (' wsyht ')) #执行函数, the second method of invocation, which is not widely known.


#map的使用, all numbers are added, subtracted, multiplied, etc.

>>> print map (lambda x:x+1,[1,2,3])   #all [2, 3, 4]>>> li  = [11,22,33]     #第一种方法 >>> temp=[]>>> for item  in li:temp.append (item + 100) ...  >>> print temp[111, 122,  133]>>> def foo (ARG):return arg + 100     #第二种方法 ...  >>> li = [11,22,33]>>> temp=[]>>> for item  in li:temp.append (foo (item)) ... >>> print temp[111, 122, 133]> >> def foo (ARG):return arg + 100    #使用map的方法 ... >> > li = [11,22,33]>>> temp = map (Foo,li) >>> print  Temp[111, 122, 133]>>> li = [11,22,33]>>> temp = map (lambda arg:arg+100, Li)     #最简单的map方法把他便利出来 >>> print temp[111, 122, 133] 


#filter的使用, filter condition, only true sequence, will be added to him, subtraction operation

#!/usr/bin/env Python#coding:utf-8li = [2,5,11,22,33]def foo (ARG): if Arg<22:return True Else:ret Urn Falsetemp = filter (foo,li) Print Temp


#reduce的使用, cumulative, multiplicative operation

>>> li=[2,5,7]>>> Print reduce (lambda x,y:x+y,li) #最少要有两个变量x,y14>>> print reduce (lambda x, y : X*y,li) 70


#zip的使用, stitch each column of their list into a group of printed

>>> x = [4,5,6] >>> y = [+ =] >>> z = [7,8,9]>>> q = [1,3,5]>>> print zip (x , y,z,q) [(1, 4, 7, 1), (2, 5, 8, 3), (3, 6, 9, 5)]>>> q = [1,3,5] >>> x = [2,4,6]>>> Z = [2, 4] >>> print zip (q,x,z) [(1, 2, 2), (3, 4, 4)]


#eval的使用

>>> a = ' 8*8 ' >>> print a8*8>>> print eval (a) 64


#反射, the use of __import__ (), to import the module as a string, and to execute the function in the form of a string
Additional knowledge:
GetAttr () #获取模块的函数数
Hasattr () #判断模块有没有这个函数
Delattr () #删除这个模块的某个函数

#查看帮助
#import OS
#help (OS)

Demo 1: Importing a module in the form of a string

>>> temp = ' sys ' >>> model = __import__ (temp) >>> print model.path[', '/usr/local/python2.7/ Lib/python27.zip ', '/usr/local/python2.7/lib/python2.7 ', '/usr/local/python2.7/lib/python2.7/plat-linux2 ', '/usr/ Local/python2.7/lib/python2.7/lib-tk ', '/usr/local/python2.7/lib/python2.7/lib-old ', '/usr/local/python2.7/lib/ Python2.7/lib-dynload ', '/usr/local/python2.7/lib/python2.7/site-packages ']


#演示2:
The main package has three modules, index.py, mysqlserver.py,sqlserver.py

Cat mysqlserver.py#!/usr/bin/env Pythondef count (): Return 2
Cat sqlserver#!/usr/bin/env Pythondef count (): Return 2


#index. py Example 1, to import the module in the form of a string

#!/usr/bin/env python ' import mysqlserverprint mysqlserver.count () import sqlserverprint sqlserver.count () ' temp = ' MySQLServer ' #动态切换模块, the module executes under the same method, when a outage, can be quickly switched, faster than the above method convenient model = __import__ (temp) model.count ()


#index. py Example 2,

Cat index.py temp = ' mysqlserver ' #模块名字func = ' count ' #函数名字 model = __import__ (temp) #以字符串的形式导入模块function = GetAttr (Model,func) #获取model模块找func函数print function () #以字符串的形式执行函数 #val = hasattr (model, ' version ') #判断model模块里有没有version这个函数 #print val#dels = delattr (model, ' count ') #删除model模块里的count函数 #print dels

#用在开发大型程序, ready to switch the database in the scenario



"Common Modules"


This article is from the "Wsyht90 blog" blog, make sure to keep this source http://wsyht2015.blog.51cto.com/9014030/1827654

Python notes the 3rd Chapter, modules and modules of common methods, functional programming yield, ternary operation lambda expression, built-in culvert number, common modules

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.