2010/03/14

Python 简明学习笔记(二)

六:函数

函数是重用的字符串.
函数的定义通过关键词 def

def <函数名>():
<函数体>

函数的形参:参数在函数定义的圆括号内指定,用逗号分隔。
函数的实参:调用函数时,按照形参的格式交由函数处理的数据叫做实参。

eg:
#!/usr/bin/python
#Filename: func_param.py

def printMax(a,b):
    if a>b:
        print a
    else:
        print b

printMax(3,4)

局部变量:没有特殊声明,在函数内定义的变量都是局部变量,其作用域始于定义处,终止于函数结尾。

使用global语句:将变量生命为全局变量。
eg:

#!/usr/bin/python
#Filename:func_global.py
a=10
def func():
    global x
    print 'x=',x
    x=2
    print'changed local x to ',x
    a=20
    print 'a in the func is',a

x=50
print 'a in the outer is ',a
func()
print 'value of a is',a
pirnt 'value of x is ',x

output:
a in the outer is 10
x=50
changed local x to 2
value of a is 10
value of x is 2

默认参数值:对于一些函数,希望它的一些参数是可选的,如果用户互相为这类参数提供值的话,这些参数使用默认值。

eg:
#!/usr/bin/python
#Filename:func_default.py

def say(message,times=1):
    print message*times

say ('hello')
say ('world',5)

output:
hello
worldworldworldworldworld

关键参数:一个函数有多个参数,作者只想指定其中一部分,那么作者可以通过命名来为这些参数赋值,这些参数被称为关键参数,用户用名字(关键字)而不是闻之来给参数指定实参。
eg:

#!/usr/bin/python
#Filename:func_key.py

def func(a,b=5,c=10)
    print'a =',a,'b=',b,'c=',c

func(1)
func(2,c=30)
func(c=40,a=3)

output:
a=1,b=5,c=10
a=2,b=5,c=30
a=3,b=5,c=40

return语句:return语句用来从一个函数返回,即跳出函数。
eg:
#!/usr/bin/python
#Filename:func_return.py

def maxnum(x,y):
    if x>y:
        return x
    else:
        return y

print maxnum(2,3)


DocStrings,文档字符串:有点像javadoc

#!/usr/bin/python
# Filename: func_doc.py

def printMax(x, y):
'''Prints the maximum of two numbers.
The two values must be integers.'''
    x = int(x) # convert to integers, if possible
    y = int(y)
    if x > y:
        print x, 'is maximum'
    else:
        print y, 'is maximum'

printMax(3, 5)
print printMax.__doc__  #双下划线,Python中的
            #help()命令其实就是抓取程序的__doc__属性

output:
$ python func_doc.py
5 is maximum
Prints the maximum of two numbers.
The two values must be integers.



七:模块
模块基本上是一个包含了所有你定义的函数和变量的文件。模块文件必须以.py为扩展名。
模块可以从其他程序调入,以便利用它的功能。这也是我们使用Python标准库的方法。

#!/usr/bin/python
#Filename:using_sys.py

import sys

print 'the command line arguments are:'
for i in sys.argv:
    print i

print'\n\n the pythonpath is :\n',sys.path,'\n'


output:
$python using_sys.py we are arguments
the command line arguments are:
using_sys.py
we
are
arguments
the pythonpath is :
['/home/swaroop/byte/code', '/usr/lib/python23.zip',
'/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2',
'/usr/lib/python2.3/lib-tk', '/usr/lib/python2.3/lib-dynload',
'/usr/lib/python2.3/site-packages', '/usr/lib/python2.3/site-packages/gtk-2.0']

#字节编译的.pyc文件:程序处理一个模块比较耗费资源,如果将模块编译成字节码的.pyc为扩展名的文件,效率将大大提高。这些字节码也是与平台无关的。

#from...import语句:
如果你想要直接输入argv变量到你的程序中(避免在每次使用它时打sys.),那么你可以使用from sys import argv语句。如果你想要输入所有sys模块使用的名字,那么你可以使用from sys import *语句。这对于所有模块都适用。一般说来,应该避免使用from..import而使用import语句,因为这样可以使你的程序更加易读,也可以避免名称的冲突。

模块的__name__属性:模块的名字
使用__name__属性的一种情况:当模块第一次被import时,这个模块的主模块就会被运行,假如我们只希望在程序被使用的时候运行模块,而不是在它被别动载入的时候,可以通过此属性完成。

#!/usr/bin/python
#Filename:using_name.py

if __name__=='__main__':
    print 'this program is being running by itself '
else:
    print:'i am bing imported from another module'

输出:
$python using_name.py
this program is being running by itself
$python
>>>imort using_name.py
i am bing imported from another module
>>>


创建用户模块:每个python程序都是一个模块
eg:
#!/usr/bin/python
#Filename:mymodule.py

def sayhello():
    print'hello ,this is mymodule speaking.'
version='0.1'
#end of mymodule.py
#注意:此模块需要被放置在import它程序的同一目录,或放在sys.path中。

#!/usr/bin/python
#Filename:using_mymodule.py

import mymodule
mymodule.sayhello()
print 'version:' ,mymodule.version

output:
hello ,this is mymodule speaking
version:0.1



dir()函数:内建函数,列出模块定于的标识符(包含函数.类.变量等)
eg:
$python
>>>import sys
>>> dir (sys) #get list of attributes of sys module
.....
>>>dir() #get list of attributes of current module
.....
>>>a=5 #create a new variable 'a'
>>>dir()
.....
['__builtins__', '__doc__', '__name__', 'a', 'sys']
>>>del a #delete/remove a name
>>>dir()
.....
>>>


八:解决问题:python脚本

备份脚本 version 1:

#!/usr/bin/python
#Filename:backup_ver1.py

import os
import time

#the files and dirs that you wanna to backup
#if you are using windows,use source=[r'c:\documents',r'd:\dev']
source=['/home/anix/document','/etc/','/usr/bin/']

#the directory that the backup files are stored
target_dir='/media/backup/'

#the name of the backup archieve
target=target_dir+os.sep+time.strftime(%Y%m%d%H%M%S')+'.tar.gz'

#the command string
tar_command="tar -cvzf %s %s"%(target,''.join(source))

#run the script
if os.system(tar_command)==0:
    print'successful backup to',target
else:
    print'backup failed'




#!/usr/bin/python
#Filename:backup_ver2.py

import os
import time

source=['/home/anix','/etc/']
target_dir='/media/backup'
today=target_dir+time.strftime('%Y%m%d')
now=time.strftime('%H%M%S')

if not os.path.exists(today):
    os.mkdir(today)
    print'successfully created directory',today
target=today+os.sep+now+'.tar.gz'

tar_command='tar cvzf %s %s' %(target,''.join(source))

if os.system(tar_command)==0:
    print'successful backup to ',target
else:
    print'backup failed'


软件开发过程:分析->设计->编写->测试->使用->维护(优化)

没有评论:

发表评论