自动化测试脚本语言-Python 读书笔记

 

python读书笔记

 

1         格式说明

 

1,  同一层次的语句必须有相同的缩进。每一组这样的语句称为一个

2,   行结束符号

每个块语句(函数defif, elseforwhile等) 开始的行 结束

其他的行 没有结束符号,也可以有分号;

3,   注释 符号 #

4,   区分大小写??

5,   赋值语句:    使用等号=

条件判断语句:使用双等号==

6,变量不需要申明,直接使用

 

2         函数

函数通过def关键字定义def关键字后跟一个函数的 标识符 名称,然后跟一对圆括号。圆括号之中可以包括一些变量名,该行以冒号结尾。接下来是一块语句,它们是函数体。下面这个例子将说明这事实上是十分简单的:

 

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

printMax(3, 4) # directly give literal values

 

2.1   默认参数值

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

say('Hello')
say('World', 5)

 

关键参数

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

func(3, 7)
func(25, c=24)
func(c=50, a=100)

 

 

pass语句在Python中表示一个空的语句块。

def someFunction():
    pass

 

2.2   在函数中接收元组和列表

当要使函数接收元组字典形式的参数的时候,有一种特殊的方法,它分别使用***前缀。这种方法在函数需要获取可变数量的参数的时候特别有用。

>>> def powersum(power, *args):
...     '''Return the sum of each argument raised to specified power.'''
...     total = 0
...     for i in args:
...          total += pow(i, power)
...     return total
...
>>> powersum(2, 3, 4)
25    =  3
2+ 42

>>> powersum(2, 10)
100

由于在args变量前有*前缀,所有多余的函数参数都会作为一个元组存储在args。如果使用的是**前缀,多余的参数则会被认为是一个字典的键/值对

 

3         模块

为了在其他程序中重用模块,模块的文件名必须.py为扩展名。

3.1   import

import sys

 

Python下标从0开始计数,而非从1开始。

 

字节编译的.pyc文件

这些字节编译的文件也是与平台无关的。

3.2   from..import语句

如果你想要直接输入argv变量到你的程序中(避免在每次使用它时打sys.),那么你可以使用

from sys import argv语句。如果你想要输入所有sys模块使用的名字,那么你可以使用

from sys import *语句。这对于所有模块都适用。一般说来,应该避免使用from..import而使用import语句,因为这样可以使你的程序更加易读,也可以避免名称的冲突

3.3   _name_

当一个模块被第一次输入的时候,这个模块的主块将被运行。假如我们只想在程序本身被使用的时候运行主块,而在它被别的模块输入的时候不运行主块,我们该怎么做呢?这可以通过模块的__name__属性完成。

if __name__ == '__main__':
    print 'This program is being run by itself'
else:
    print 'I am being imported from another module'

3.4   使用global语句

如果你想要为一个定义在函数外的变量赋值,那么你就得告诉Python这个变量名不是局部的,而是 全局 的。我们使用global语句完成这一功能。没有global语句,是不可能为定义在函数外的变量赋值的。

你可以使用同一个global语句指定多个全局变量。例如global x, y, z

3.5   创建你自己的模块

个模块应该被放置在我们输入它的程序的同一个目录中,或者在sys.path所列目录之一

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


def sayhi():
    print 'Hi, this is mymodule speaking.'

version = '0.1'

# End of mymodule.py

 

说明: 文件名.py 相当于类名 /结构名,里面的函数相当于成员函数,里面的变量相当于成员变量

3.6   使用自己的模块

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


import mymodule

mymodule.sayhi()
print 'Version', mymodule.version

4         数据结构

4.1   列表【中括号】

由于你可以增加或删除项目,我们说列表是 可变的 数据类型,即这种类型是可以被改变的。

你可以在列表中添加 任何种类的对象 包括数甚至其他列表

shoplist = ['apple', 'mango', 'carrot', 'banana']

print 'I have', len(shoplist),'items to purchase.'

print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
    print item,

print '/nI also have to buy rice.'
shoplist.append('rice')
print 'My shopping list is now', shoplist

shoplist.sort()     这个方法影响列表本身,而不是返回一个修改后的列表

olditem = shoplist[0]
del shoplist[0]

 

i = []
 i.append('item')

4.2   列表综合

通过列表综合,可以从一个已有的列表导出一个新的列表。例如,你有一个数的列表,而你想要得到一个对应的列表,使其中所有大于2的数都是原来的2倍。对于这种应用,列表综合是最理想的方法。

listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print listtwo

4.3   元组 (小括号)

元组和列表十分类似,只不过元组和字符串一样是 不可变的 即你不能修改元组。元组通过圆括号中用逗号分割的项目定义

age = 22
name = 'Swaroop'
print '%s is %d years old' % (name, age)

4.4   字典{大括号},引用时用[中括号]

字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿,即,我们把(名字)和(详细情况)联系在一起。注意,键必须是唯一的,就像如果有两个人恰巧同名的话,你无法找到正确的信息。

注意,你只能使用不可变的对象(比如字符串)来作为字典的,但是你可以不可变或可变的对象作为字典的。基本说来就是,你应该只使用简单的对象作为键。

d = { key1 : value1, key2 : value2 }

注意它们的/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中

ab = {       'Swaroop'   : '[email protected]',
             'Larry'     : '[email protected]',
             'Matsumoto' : '[email protected]',
             'Spammer'   : '[email protected]'
     }
print "Swaroop's address is %s" % ab['Swaroop']

# Adding a key/value pair
ab['Guido'] = '[email protected]'       添加

# Deleting a key/value pair
del ab['Spammer']                         删除

print '/nThere are %d contacts in the address-book/n' % len(ab)
for name, address in ab.items():
    print 'Contact %s at %s' % (name, address)

if 'Guido' in ab: # OR ab.has_key('Guido')
    print "/nGuido's address is %s" % ab['Guido']

4.5   序列

列表、元组和字符串都是序列,

索引同样可以是负数,在那样的情况下,位置是从序列尾开始计算的。

因此,shoplist[-1]表示序列的最后一个元素shoplist[-2]抓取序列的倒数第二个项目

name = 'swaroop'
print 'characters 1 to 3 is', name[1:3]
print 'characters 2 to end is', name[2:]
print 'characters 1 to -1 is', name[1:-1]
print 'characters start to end is', name[:]

注意,返回的序列从开始位置 开始 ,刚好在 结束 位置之前结束。即开始位置是包含在序列切片中的,而结束位置被排斥在切片外

for i in range(1, 5):
    print i
else:
    print 'The for loop is over'

 

range(1,5)给出序列[1, 2, 3, 4]

 

如果我们为range提供第三个数,那么它将成为步长。例如,range(1,5,2)给出[1,3]

4.6   列表引用与 复制

shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist               引用

mylist = shoplist[:] # make a copy by doing a full slice   复制

4.7   字符串

name = 'Swaroop' # This is a string object

if name.startswith('Swa'):
    print 'Yes, the string starts with "Swa"'

if 'a' in name:
    print 'Yes, it contains the string "a"'

if name.find('war') != -1:
    print 'Yes, it contains the string "war"'

delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist)   

  最后一行结果: Brazil_*_Russia_*_India_*_China

4.8   DocStrings

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__

 

输出:

5 is maximum
Prints the maximum of two numbers.

        The two values must be integers.

5         使用类

5.1   成员函数

类中的函数 第一个参数都是self

class Person:
    def __init__(self, name):
        self.name = name

    def sayHi(self):
        print 'Hello, my name is', self.name

p = Person('Swaroop')
成员函数中的第一个变量 self 当前类 那个对象   相当于 this

__init__  这个名称的开始和结尾都是双下划线  构造函数

__del__       析够函数

     当对象不再被使用时,__del__方法运行,但是很难保证这个方法究竟在 什么时候行。如果你想要指明它的运行,你就得使用del语句,就如同我们在以前的例子中使用的那样

5.2   成员变量

有两种类型的 ——类的变量(静态变量)和对象的变量,

它们根据是类还是对象 拥有 这个变量而区分

类的变量(相当于静态变量):    在类中用类名.变量 应用    需要先定义

                                 C++成员变量定义位置初始化

对象的变量: 在类中用 self.变量  使用

             在成员函数中 直接用self 引用 ,不需要先定义

能使用self变量来参考同一个对象的变量和方法。这被称为 属性参考

5.3   公共变量与私有变量

      Python中所有的类成员(包括数据成员)都是 公共 ,所有的方法都是 有效的,如果你使用的数据成员名称以 双下划线前缀 比如__privatevarPython的名称管理体系会有效地把它作为私有变量

 

6         继承

   为了使用继承,我们把基本类的名称作为一个元组跟在定义类时的类名称之后。然后,我们注意到基本类的__init__方法专门使用self变量调用,这样我们就可以初始化对象的基本类部分。这一点十分重要——Python不会自动调用基本类的constructor,你得亲自专门调用它。

     如果在继承元组中列了一个以上的类,那么它就被称作 多重继承

class SchoolMember:

        pass

class Teacher(SchoolMember):

     pass

 

 

7         文件操作

7.1   读一般文件

poem = '''/
Programming is fun
When the work is done
if you wanna make your work also fun:
        use Python!
'''


f = file('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file

f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
    line = f.readline()

    if len(line) == 0: # Zero length indicates EOF
        break
    print line,
    # Notice comma to avoid automatic newline added by Python
f.close() # close the file

7.2   INI文件

import ConfigParser

 

filename=’c:my.ini’

config = ConfigParser.ConfigParser()

config.readfp(open(fileName))   

execTimes = config.get("GLOBAL_CONFIG", "execTimes")

 

 

8         持久化对象-储存器

     Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象

     还有另一个模块称为cPickle,它的功能和pickle模块完全相同,只不过它是用C语言编写的,因此要快得多(比pickle1000倍)。

import cPickle as p
#import pickle as p

shoplistfile = 'shoplist.data'
# the name of the file where we will store the object

shoplist = ['apple', 'mango', 'carrot']

# Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file

f.close()

del shoplist # remove the shoplist

# Read back from the storage

f = file(shoplistfile)
storedlist = p.load(f)

print storedlist

调用储存器模块的dump函数,把对象储存到打开的文件中。这个过程称为 储存

接下来,我们使用pickle模块的load函数的返回来取回对象。这个过程称为 取储存

 

9         异常

如果某个错误或异常没有被处理,默认的Python处理器就会被调用。它会终止程序的运行,并且打印一个消息,我们已经看到了这样的处理。

import sys

try:
    s = raw_input('Enter something --> ')
except EOFError:
    print '/nWhy did you do an EOF on me?'
    sys.exit() # exit the program
except:
    print '/nSome error/exception occurred.'
    # here, we are not exiting the program

print 'Done'

 

引发异常

你可以使用raise语句 引发 异常。你还得指明错误/异常的名称和伴随异常 触发的 异常对象。你可以引发的错误或异常应该分别是一个ErrorException类的直接或间接导出类。

class ShortInputException(Exception):
    '''A user-defined exception class.'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast


try:
    s = raw_input('Enter something --> ')

    if len(s) < 3:
        raise ShortInputException(len(s), 3)

    # Other work can continue as usual here
except EOFError:
    print '/nWhy did you do an EOF on me?'
except ShortInputException, x:           异常类,异常变量
    print 'ShortInputException: The input was of length %d, /
          was expecting at least %d' % (x.length, x.atleast)

else:
    print 'No exception was raised.'

finally:

pass

10    os模块

这个模块包含普遍的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在LinuxWindows下运行。一个例子就是使用os.sep可以取代操作系统特定的路径分割符。

下面列出了一些在os模块中比较有用的部分。它们中的大多数都简单明了。

·         os.name字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'

·         os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径

·         os.getenv()os.putenv()函数分别用来读取和设置环境变量

·         os.listdir()返回指定目录下的所有文件和目录名

·         os.remove()函数用来删除一个文件。

·         os.system()函数用来运行shell命令。

·         os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用'/r/n'Linux使用'/n'Mac使用'/r'

·         os.path.split()函数返回一个路径的目录名和文件名

·         os.path.isfile()os.path.isdir()函数分别检验给出的路径是一个文件还是目录。类似地,os.path.existe()函数用来检验给出的路径是否真地存在。

你可以利用Python标准文档去探索更多有关这些函数和变量的详细知识。你也可以使用help(sys)等等。

11    其他

11.1       特殊的方法

__init__(self,...)

这个方法在新建对象恰好要被返回使用之前被调用。

__del__(self)

恰好在对象要被删除之前调用。

__str__(self)

在我们对对象使用print语句或是使用str()的时候调用

__lt__(self,other)

当使用 小于 运算符(<)的时候调用。类似地,对于所有的运算符(+>等等)都有特殊的方法。

__getitem__(self,key)

使用x[key]索引操作符的时候调用。

__len__(self)

对序列对象使用内建的len()函数的时候调用。

 

11.2       lambda形式

lambda语句被用来创建新的函数对象,并且在运行时返回它们。

11.3       execeval语句

exec语句用来执行储存在字符串或文件中的Python语句。例如,我们可以在运行时生成一个包含Python代码的字符串,然后使用exec语句执行这些语句。下面是一个简单的例子。

>>> exec 'print "Hello World"'

Hello World

eval语句用来计算存储在字符串中的有效Python表达式。下面是一个简单的例子。

>>> eval('2*3')
6

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章