简单的入门书_A Byte of Python书评-查字典图书网
查字典图书网
当前位置: 查字典 > 图书网 > 编程 > A Byte of Python > 简单的入门书
阿杜 A Byte of Python 的书评 发表时间:2013-04-22 21:04:22

简单的入门书

        这几天由于应用需要,学习了一下python,百度一搜,这本书就在前三,进去一看,感觉挺简单的,看起来轻松,书也不厚,这两天随便翻翻就看完了。网上翻译版在http://sebug.net/paper/python/index.html,英文原版在http://www.ibiblio.org/g2swap/byteofpython/read/index.html。翻译的作者是学通信出身的,有点出乎意料,翻译还算可以,有些地方不是太好,像“reference”应该翻译成“引用”等,不过这都不妨碍理解,感觉不对了对照一下原版的看就可以了。
        总的来说入门没问题,看完之后至少可以看懂别人写的代码,自己要写一些高级点的程序的话还需要再找一些资料。
        看完后python给我的感觉就像读英文,一看就能大概知道一条语句要做什么,而且比C++、Java这种大型语言简单、灵活,用起来比较方便。
        下面是我看书过程中的一些笔记:

        * 基础:
        *
                * 语句控制块

        *
                *
                        * if-elif-else,注意在每个关键字语句最后加冒号:如

                *
                        *
                                * if guess == number:
    print 'Congratulations, you guessed it.' # New block starts here

                        * while同样需要最后冒号,同时while结束后可加else,效果与不加相同:如
                        *
                                * while running:
    guess = int(raw_input('Enter an integer : '))
else:
    print 'The while loop is over.'
print 'Done'

                        * for语句和一般的C++和Java不同,使用的是for ... in ...的形式,同样是用冒号:结束,可以加else,如:
                        *
                                * for i in range(1, 5):
    print i
else:
    print 'The for loop is over'

                        * break语句跟其他语言相同,用户终止循环,但有个不同的地方,循环被终止后else语句块的语句将不被执行

                * 函数
                *
                        * 函数定义:“def 函数名(参数列表) :”,其中参数列表是值传递,不是引用传递
                        * 可使用global说明使用一个函数外定义的变量,但尽量避免这么做,如:
                        *
                                * def func():
    global x
    print 'x is', x

                        * 默认参数:参数名=默认值,默认参数需要在参数列表的末尾,调用函数时如果没有参数也需要带空括号,如:
                        *
                                * def say(message, times = 1):
    print message * times

                        * 关键参数:改变函数调用的传参顺序,通过形参名字进行赋值,可以和默认参数结合使用,只改变部分想改变的默认参数值,如:
                        *
                                * 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)

                        * 没有return语句的函数默认return None,None是python表示没有任何东西的特殊类型
                        * pass表示python的空语句块,如:
                        *
                                * def someFunction():
    pass

                        * 文档字符串DocStrings:每个函数、类、模块最好都有文档字符串描述他们的功能,通过"对象.__doc__"可以获得他们的文档字符串。文档字符串的惯例:1. 多行字符串,通过'''表示;2. 首行以大写字母开始,句号结束;3. 第二行为空行;4. 第三行开始是详细描述。如:
                        *
                                * 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__


                * 模块
                *
                        * sys模块:模块以.py为后缀,通过import输入使用模块,包含python解释器和环境的有关参数,在第一次输入模块的时候初始化,其中argv属性表示命令行的参数,path属性表示输入模块的目录名列表
                        * 字节编译文件.pyc:输入.py后缀的模块需要翻译成中间字节编译文件的过程,比较耗时,.pyc文件是字节编译文件,速度快
                        * from ... import语句:和C++的using namespace类似,引入import模块里的一些常用名字,方便使用,而不用每次都通过类似sys.argv的方式,直接使用argv。不过尽量少这样用,减少名字冲突
                        * 模块的__name__:默认没设置时,一个模块可以直接运行主体代码,也可以在导入其他模块时运行主体代码。通过设置__name__的值为__main__可以让一个模块作为一个单独功能直接运行,而在被引入其他模块时不运行,如:
                        *
                                * if __name__ == '__main__':
    print 'This program is being run by itself'
else:
    print 'I am being imported from another module'
                                * 如果直接./testmodule.py,则显示This program is being run by itself,如果通过其他python文件import testmodule,则显示I am being imported from another module

                        * dir():用于列出所使用模块的属性列表,包括函数、类、变量,如果为其没有提供参数,则返回当前模块的属性列表
                        * del:类似于C++中的delete,用于删除一个变量/名称,删除后就不能再用这个变量/名称

                * 数据结构
                *
                        * 列表:用[]存储,可以通过添加、删除、排序修改列表,可以通过len(列表)取得长度、通过数组下标方式访问(从0开始),如:
                        *
                                * 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

print 'I will sort my list now'
shoplist.sort()
print 'Sorted shopping list is', shoplist
print 'The first item I will buy is', shoplist[0]
olditem = shoplist[0]
del shoplist[0]
print 'I bought the', olditem
print 'My shopping list is now', shoplist

                        * 元组:和列表类似,用()存储,可以通过数组下标方式访问(从0开始),但元组值不可改变。而且如果元组只有一个元素时,需要在元素后面加一个逗号,以区分表达式中一个带圆括号的对象。元组内的元素保持原来的身份,即如果在元组内添加的元素是一个元组,则根据下标访问到时返回的还是一个元组,如:
                        *
                                * zoo = ('wolf', 'elephant', 'penguin')
print 'Number of animals in the zoo is', len(zoo)
new_zoo = ('monkey', 'dolphin', zoo)
print 'Number of animals in the new zoo is', len(new_zoo)
print 'All animals in new zoo are', new_zoo #此时返回结果是('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))
print 'Animals brought from old zoo are', new_zoo[2]
print 'Last animal brought from old zoo is', new_zoo[2][2]
                                * 元组一般用于打印语句,如:
                                *
                                        * age = 22
name = 'Swaroop'
print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name


                        * 字典:相当于Map,一种key-value形式,其中key的必须是不可变的对象,value可以变也可以不变,,通过下标访问法传入key值进行访问,可以通过items()返回字典的key-value对,用in关键字或者has_key()方法判断一个key是否在字典中,如:
                        *
                                * ab = { 'Swaroop' : 'swaroopch@byteofpython.info',
             'Larry' : 'larry@wall.org',
             'Matsumoto' : 'matz@ruby-lang.org',
             'Spammer' : 'spammer@hotmail.com'
     }

print "Swaroop's address is %s" % ab['Swaroop']
ab['Guido'] = 'guido@python.org' #增加一项
del ab['Spammer']
print 'nThere are %d contacts in the address-bookn' % 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']

                        * 序列:列表、元组、字符串都是序列,序列的好处就是可以用相同的方式访问序列的内容(数组下标),都可以切片:类似于[0:2]之类的冒号分割的数字,用于获取序列中的一个子集,其中数字可以没有,但冒号必须有,第二个数字不在子集范围内,缺省第一个数字表示从序列头开始,缺省第二个数字表示到序列结尾。如:
                        *
                                * shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'Item 0 is', shoplist[0]
print 'Item -1 is', shoplist[-1]
print 'Item 1 to 3 is', shoplist[1:3]
print 'Item 2 to end is', shoplist[2:]
print 'Item 1 to -1 is', shoplist[1:-1]
print 'Item start to end is', shoplist[:]

                        * 引用:相当于C++中的指针或者引用,如果创建一个变量时只是赋予一个变量,该变量只是一个引用,两个变量指向是同一个内存空间,要实现深度复制必须使用切片,即“变量名[:]”
                        * 一些字符串方法:in、startswith、find、join,其中前三个用于判定是否存在某一子串,join用于使用该字符串来连接一个列表以形成一个大的字符串,如:
                        *
                                * delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist) #结果为: Brazil_*_Russia_*_India_*_China


                * 一个简单的应用示例python程序:备份重要文件
                *
                        * 通过使用(import)os模块的system方法调用linux的命令,其返回值与shell命令类似,0表示成功执行,1表示执行失败,据说不推荐直接使用system方法,可能os模块有linux系统每个shell命令对应的名字标识。如:
                        *
                                * zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
    print 'Successful backup to', target
else:
    print 'Backup FAILED'

                        * os模块的path方法用于路径操作,mkdir方法用于创建文件夹,sep表示路径分隔符(linux为/,windows为,mac为:),如:
                        *
                                * if not os.path.exists(today):
    os.mkdir(today) # make directory
    print 'Successfully created directory', today
# The name of the zip file
target = today + os.sep + now + '.zip'

                        * raw_input用于获取用户界面输入如:
                        *
                                * comment = raw_input('Enter a comment --> ')


                * 面向对象编程
                *
                        * 类由关键词“class 类名”定义
                        * self:类的方法必须有一个self参数,且位于第一个,但在调用时不需要为这个参数赋值,这个参数执行对象本身,如:
                        *
                                * class Person:
    def sayHi(self):
        print 'Hello, how are you?'
p = Person()
p.sayHi()

                        * 创建类对象:“对象名=类名(参数列表)”,如:
                        *
                                * class Person:
    pass # An empty block
p = Person()
print p

                        * __init__:类似于C++、Java中的构造函数,如:
                        *
                                * class Person:
    def __init__(self, name):
        self.name = name
    def sayHi(self):
        print 'Hello, my name is', self.name
p = Person('Swaroop')
p.sayHi()

                        * __del__:类似于C++的析构函数,在对象消逝的时候被调用,如果要显示删除一个对象,使用del语句
                        * 类变量和对象变量:类似于C++和Java的static变量,类变量由“类名.类变量名”表示,对象变量由“self.对象变量名”表示,如:
                        *
                                * class Person:
    '''Represents a person.'''
    population = 0
    def __init__(self, name):
        '''Initializes the person's data.'''
        self.name = name #对象变量
        print '(Initializing %s)' % self.name
        # When this person is created, he/she
        # adds to the population
        Person.population += 1 #类变量

                        * 继承:通过在类名后面加一个元组,元组的元素为要继承的父类;python不会自动初始化父类,需要在子类的__init__中调用父类的__init__方法,且通过父类名调用,需要传入self参数;子类中调用的父类的方法也类似,使用父类名调用,传入self参数,如:
                        *
                                * class SchoolMember:
    '''Represents any school member.'''
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print '(Initialized SchoolMember: %s)' % self.name
    def tell(self):
        '''Tell my details.'''
        print 'Name:"%s" Age:"%s"' % (self.name, self.age),

class Teacher(SchoolMember):
    '''Represents a teacher.'''
    def __init__(self, name, age, salary):
        SchoolMember.__init__(self, name, age)
        self.salary = salary
        print '(Initialized Teacher: %s)' % self.name
    def tell(self):
        SchoolMember.tell(self)
        print 'Salary: "%d"' % self.salary


                * 输入/输出
                *
                        * 文件:file方法打开文件,模式有r,w,a,默认为r,有read,readline,write方法,如:
                        *
                                * 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

                        * pickle:相当于Java的序列化,用于存储一个对象到文件中,有pickle和cPickle两个模块,cPickle是C语言实现的,比pickle快1000倍。通过dump存储一个对象到文件,通过load把一个对象从文件中读取出来。import ... as ...可以对模块起别名,在程序中使用别名相当于使用这个模块,类似于C++中的宏定义。如:
                        *
                                * import cPickle as p
shoplistfile = 'shoplist.data'
shoplist = ['apple', 'mango', 'carrot']
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file
f.close()
del shoplist # remove the shoplist
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist


                * 异常
                *
                        * try ... except ... [else ...]:类似于Java的try...catch...,except可以跟元组,元组是可能发生的异常类型,如果except后没有跟内容,则捕获所有异常。和while、for语句类似,try...except后还可以跟else从句,当没有异常发生时,else从句执行。如:
                        *
                                * try:
    s = raw_input('Enter something --> ')
except EOFError:
    print 'nWhy did you do an EOF on me?'
    sys.exit() # exit the program

                        * 创建自己的异常:和Java的异常处理机制相同,用户可以定义自己的异常,只需继承Error或者Exception类即可,通过raise抛出异常对象,在except中获取使用这个对象,except格式:“except 异常类型, 对象名”,Python2.6之后应写作“except 异常类型 as 对象名”,显然比原来那个版本易理解多了,如:
                        *
                                * 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)

                        * finally:与Java类似,无论异常发生与否都会执行的代码块,与else不同,else的代码块只有不发生异常时才会执行,据说2.5版本以前的不支持except和finally一起使用,2.5之后才支持,系统装的是2.6版本的python解释器,没试过不行的例子。示例:
                        *
                                * import time

try:
    f = file('poem.txt')
    while True: # our usual file-reading idiom
        line = f.readline()
        if len(line) == 0:
            break
        time.sleep(2)
        print line,
finally:
    f.close()
    print 'Cleaning up...closed the file'


                * Python标准库
                *
                        * sys模块:argv、exit()、version、version_info、等
                        * os模块:使用这个模块可以使程序与操作系统无关,常用:sep(分隔符)、getcwd()(当前工作目录)、listdir()(获取指定目录下的所有文件和目录名)、remove()(删除一个文件)、system()(用来执行shell命令)、linesep(系统平台的换行符,如windows的rn,linux的n,mac的r)、path.split()(分割目录名和文件名)、path.isfile()、path.isdir()
                        * 更多模块的内容需要通过help去学习

                * Python的奇淫技巧
                *
                        * 特殊方法:__init__(self,...), __del__(self), __str__(self), __lt__(self, other), __getitem__(self, key), __len__(self),可以像C++一样进行运算符重载
                        * 列表处理:可以通过一个列表生成另外一个列表,如:
                        *
                                * listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print listtwo

                        * 函数接收元组和词典:分布通过定义形参为*和**前缀实现,可以应用于可变数量的参数,如:
                        *
                                * def test(name, *argv):
  print name
  for item in argv:
    print item,

test('adu', 1,2,3)
                                * def test(**argv):
  for item,value in argv.items():
    print 'key=%s, value=%s' % (item, value)

test(a=1,b=3)

                        * lambda表达式:如:
                        *
                                * def make_repeater(n):
    return lambda s: s*n
twice = make_repeater(2)
print twice('word') #结果为wordword

                        * exec和eval语句:exec用来执行存储在字符串中的python代码,eval用来计算存储在字符串中的python表达式,如:
                        *
                                * exec 'print "Hello World"'
                                * eval('2*3')

                        * assert语句:和C++中的类似,用来确认一个表达式是正确的,否则会抛出AssertionError
                        * repr语句:与反单引号相同,用于获取对象的规范字符串表示,即对象的可打印形式,可通过定义类的__repr__方法来控制,如:
                        *
                                * i=['item']
print `i` #结果为['item']
print repr(i) #结果为['item']


展开全文
有用 0 无用 0

您对该书评有什么想说的?

发 表

推荐文章

猜你喜欢

附近的人在看

推荐阅读

拓展阅读