python headfirst 笔记

英语单词

Redundance: 冗余,多余

Intentional:故意的,企图的,策划的

stuff[stʌf]

n.材料, 原料; 物品, 东西; 木料; 纺织品

v.塞满, 填充, 填满; 饱食, 吃得过多

indented[in·dent·ed || ɪn'dentɪd]

adj.锯齿状的; 受契约约束的; 缩进排印的

blown1[bləʊn]

adj.喘气的; 被苍蝇弄赃的; 精疲力竭的; 有蝇卵附着的; 吹制的

blown (blow)2[bləʊn]

v.吹, 刮; 随风飘动; 吹动; 吹响, 鸣响; 吹; 吹掉; 吹动; 刮走; 使开花; 开

blow[bləʊ]

n.吹动, 吹气; 吹牛, 自夸; 强风, 暴风#一击, 殴打; 不幸; 打击; 精神上的打击#开花

v.吹, 刮; 随风飘动; 吹动; 吹响, 鸣响; 吹; 吹掉; 吹动; 刮走; 使开花; 开

full blown

完全成熟的; 具有一切特征的; 充分发展的

scratch[skrætʃ]

v.抓, 搔(痒), 划破, 划掉

n.抓痕, 乱写,抓的声音, 起跑线

adj.无让步的

tricky['triki]

adj.棘手的, 狡猾的, 巧妙的

shrink[ʃrɪŋk]

n.收缩, 畏缩, 萎缩

v.收缩, 萎缩, 退缩; 使收缩, 使缩小

appropriate[ap·pro·pri·ate || ə'prəʊprɪət]

v. 拨出; 挪用, 盗用; 占用

adj. 适当的, 恰当的, 相称的

pickle ['pikl]  

n.腌汁, 泡菜, <英口>淘气鬼, <口>困境

v.腌, 泡

comprehend[com·pre·hend ||‚kɒmprɪ'hend]

v.领会; 包括; 理解

duplicate[du·pli·cate ||'djuːplɪkət]

n.副本, 复制品, 复本

adj.复制的, 二重的

v.复制; 影印, 拷贝; 复写; 重复

sanitize['sænitaiz]

vt. 采取卫生措施使其安全, 消毒, 使无害

 

 

1. Meet python

 Python is a lot like any other general-purposeprogramming language, with statements,  expressions , operators ,  functions ,  modules, methods, and  classes .

IDEL是Python的编辑环境,TAB键可以给出提示语句

Alt-P重复之前的命令,比如上一个命令是print,再向上是1+2命令,则按一次Alt-P会出现print命令,按两次出现1+2命令

Alt-N重复下一个命令,其实是循环到第一个命令。之后在向下。

 

Create simple Python lists

创建一个list在Python中非常容易,比如:

 Python’s variable identifiers don’t have a type.

When you createa list in Python, the interpreter creates an array-like data structure inmemory to hold your data, with your data items stacked from the bottom up.

Python的list也是以0为下标开始。

虽然python中变量没有类型的,但是List有集合的方法,比如len(movies),也可以使用append()方法向list后面添加数据,可以使用pop()方法把最后添加的数据弹出,使用extend()方法在后面添加集合等,如下:

也可以使用remove(元素值)的方式删除元素,使用insert(下标,元素)的方式在特定位置插入元素,如:

Add more data to your list

向list中添加更多数据,有两种选择:

1.选择合适的list方法来添加

2.当数据少的时候,重新创建list

比如在上面的movies中,要向每部电影后面加上上映时间,结果变为:

第一种方式如下:

第二种则是:

即重新建立一个list

因为数据比较少,使用第二种方式比较好。

Work with your list data

使用for遍历list,比如:

主要:不用忘记“:”

当然也可以使用while语句:

 

Python中的字符串可以以双引号“或者是单引号’包围,他们没有区别。如果想要在字符串中包含双引号,则可以使用\”转义字符方式,或者使用单引号包围。

Store lists within lists

List元素中也可以是list,比如:

相当于是多维数组,比如:

遍历内嵌list的list,如下:

Check a list for a list

Python内置的方法isinstance(obj, 内置类型),可以用来判断变量是否为内置对象的一种,比如:

因此可以变量内嵌list的list时,可以使用if...else语句判断,如下:

Python内置了70多个函数,可以使用dir(__builtins__)列出所有函数,如下:

可以使用help(内置命令)方法找到该内置函数的帮助。

create a function

刚才遍历内嵌list的list时,对于多层嵌套的不能达到最内层。如果一直使用if...else语句会非常繁琐。可以使用递归的方式,首先定义一个函数,如下:

2.share yourcode:modules of functions

模块化实际就是把函数保存在.py文件中。

Python使用’’’三个单引号’’’包围的方式写注释。也可以使用#方式添加注释

查看电脑上都有哪些model,如下:

打开.py文件,然后F5,或者在IDEL上点击运行,会出现如下:

实际就是进入了该模块的运行环境,如下:

Prepare your distribution

为了分享创建的模块,需要准备一个distribution。步骤如下:

1. 创建一个目录,比如nester,创建一个nester.py文件

2. 在该目录下编写名为setup.py的文件,该文件包含distribution的元信息。信息如下:

from distutils.core import setup

 

setup(

        name = 'nester',

        version = '1.0.0',

        py_modules = ['nester'],

        author = 'mushui',

        author_email = 'liuluo129@163.com',

        url = 'www.mushui.com',

        description = 'a simple list',

    )

3. Build adistribution file. Open a terminal window within your nester folder and type asingle command:python3 setup.py sdist,在windows下使用“C:\Python32\python.exe”来代替python3,运行结果如下:

4. Installyour distribution into your local copy of Python:Staying int the terminal, type this command: sudo python3 setup.py install.结果如下:

这样在本地的Python中就导入了这个模块,安装前后目录文件为:

在windows下dist目录为.zip,且没有nester.pyc文件。

这时就可以使用了,例子如下:

注意:一定不要忘记了nester命名空间,否则会报错。因为Python默认进入命名空间为:__main__。

也可以使用import nester.print_list,类似于Java的静态导入:

import staticjava.lang.Math.sin

这样可以不使用命名空间,直接用print_list,但是如果在当前命名空间中也有这个函数,就会覆盖掉。

Build-In-Functions

Python有70多个BIF,因此在写代码的时候,首先考虑能否用到,比如range(int)可以返回一个数字的list,比如:

int(string)把一个字符串转换成一个整数(如果可以)

BIF并非是默认的__main__命名空间下的,他们属于__buildins__。

.Unlike compiledlanguages (such as C, Java, C#, and others), Python doesn’t completely  check the validity of your code until itruns.

带默认值的参数

定义的函数参数在定义时可以设定默认值,在调用该函数的时候可以不设定这个参数,如下:

也可以在中间添加一个布尔型参数,指示是否要有缩进,比如:

3. File andException

File Process

The basic inputmechanism in Python is line based: when read into your program from atext file, data arrives one line at a time.

Python’s open() BIF lives to interact with files.下面是个例子:

os是内置的模块,os.getcwd()得到当前目录,os.chdir()转换当前工作目录。

readline()是文件的方法,读取当前iterator的行,seek(0)表示iterator回到第1行。

sketch.txt文本内容如下:

Man: Is this the right room for an argument?

Other Man: I've told you once.

Man: No you haven't!

Other Man: Yes I have.

Man: When?

Other Man: Just now.

Man: No you didn't!

Other Man: Yes I did!

...

类似于对话形式,如果把冒号:变为said:,如下:

split方法,类似于Java中的字符串拆分方法,第三行代码相当于把each_line根据冒号拆分,赋给两个变量role, line_speak,如果没有冒号或者有多个冒号就会出错,比如:

Other Man: Nowlet's get one thing quite clear: I most definitely told you!

出错信息如下:

有太多冒号,不能赋给两个变量。

可以设定split的第二个参数,按照几个来拆分,split(‘:’, 1),如下:

但是如果遇见空行,或者没有冒号的又会出错,这样有两种方法来解决:

1.添加逻辑,比如判断是否有冒号

2.处理异常

在本场景下,使用find方法来添加逻辑,如下:

这样可以正确运行了,但是如果有其他异常呢。而且这样额外的逻辑,造成了代码碎片。

Handle Exceptions

Rather thanadding extra code and logic to guard against bad things happening, Python’s exception handling mechanism lets the error occur, spotsthat it has happened, and then gives you an opportunity to recover.

try :

code...

except:

    error-recover code

当捕获到异常后,不想处理,可以使用pass:

>>> for each_line in data:

       try:

              (role, line_speak) = each_line.split(':', 1)

              print(role, end='')

              print(' said: ', end='')

              print(line_speak, end='')

       except:

              pass

当sketch.txt文件不存在的时候,添加额外逻辑或者使用异常处理方式那种更好呢?

第一种使用os.path.exists(file)方法判断文件是否存在,第二种不判断,有异常直接处理。

Concentrate on what yourcode needs to do.

专注于业务需要,那些额外的逻辑虽然能保证程序正确执行,但并不是必须的,使用异常处理可以很好的避免多余的判断等。

第二种方式明显更好,但是上面可能出现的一行是不一样的,因为需要根据不同的异常来处理,避免异常丢失:

4. Persistent:Saving data to file

对于文件的处理,一般是打开文件,获取文件内容,进行处理。处理结果可以在屏幕上显示,也可以保存在其他文件中。比如上一章对话的例子,将不同人说的话显示,或者保存在文件中。

Open your file in write mode

可以使用write mode打开一个文件,从而可以向文件中写入内容。而print()函数,默认打印在屏幕中,还有一个参数为file,可以指定内容到文件中。这样把上面内容写入到两个文件中,如下:

这样讲将会生成两个文件:

When you useaccess mode w, Python opens your named file for writing. If the file alreadyexists, it is  cleared of its contents ,or clobbered. To  append  to a file, use access mode  a, and to open a file for writing and reading(without clobbering), use w+. If you try to open a file for writing that doesnot already exist, it is first created for you, and then opened for writing

在文件处理过程中,如果出现错误,则打开的文件将不会关闭,可以使用finally进行关闭,如下:

>>> try :

       man_file = open('man_data.txt','w')

       other_file = open('other_data.txt','w')

 

       print(man, file=man_file)

       print(other, file=other_file)

except IOError:

       print('File error')

finally:

       man_file.close()

       other_file.close()

When an erroroccurs at runtime, Python raises an exception of the specific type (suchas  IOError, ValueError , and so on).Additionally, Python creates an exception object thatis passed  as an argument to your exceptsuite.

上面方法如果文件时不存在的,比如:

>>> try:

  data = open('missing.txt')

  print(data.readline(), end='')

except IOError:

  print('File error')

finally:

  data.close()

调用close方法会有异常,类似于Java中关闭资源时判断资源是否为null一样,使用如下语句:

if ‘data’ in locals():

    data.close()

最终变为:

try:

     man_file = open('man_data.txt', 'w')

     other_file = open('other_data.txt', 'w')

     print(man, file=man_file)

     print(other, file=other_file)

 except IOError as err:

     print('File error: ' + str(err))

 finally:

     if 'man_file' in locals():

         man_file.close()

     if 'other_file' in locals():

         other_file.close()

因为在python中类似于打开文件这种操作非常频繁,python中添加了with关键字而对文件资源的释放进行管理,上面可以简化为:

try:

  with open(‘man_data.txt', ‘w') as man_file:

    pr int(man, file=man_file)

  with open(‘other_data.txt', ‘w') as other_file:

    print(other, file=other_file)

except IOError as err:

     print(‘File error: ' + str(err))

也可以合成一句:

>>> with open('man.txt', 'w') as man_data, open('other.txt', 'w') as other_data:

       print(man, file=man_data)

       print(other, file=other_data)

print内置函数,定义如下:

>>> help(print)

Help on built-in function print in module builtins:

 

print(...)

    print(value, ..., sep=' ', end='\n', file=sys.stdout)

   

    Prints the values to a stream, or to sys.stdout by default.

    Optional keyword arguments:

    file: a file-like object (stream); defaults to the current sys.stdout.

    sep:  string inserted between values, default a space.

    end:  string appended after the last value, default a newline.

Pickle your data

Python shipswith a standard library called pickle, which can save and load almost anyPython data object, including lists.相当于是Java对象的序列化。如下图:

You can, forexample, store your pickled data on disk, put it in a database, or transfer itover a network to another computer.

When you areready, reversing this process unpickles your persistent pickled data and  recreates your data  in its original form within Python’s memory:

用法非常简单,直接调用pickle的dump(data,out)方法就可以进行序列化,如下:

>>> import pickle

>>>

>>> a_list = [1, 2, 'three']

>>> with open('mydata.pickle', 'wb') as mysavedata:

       pickle.dump(a_list, mysavedata)

使用wb模式打开文件,b表示二进制方式。反序列化使用load(out)就可以:

>>> with open('mydata.pickle', 'rb') as myrestoredata:

       copy_list = pickle.load(myrestoredata)

 

>>> print(copy_list)

[1, 2, 'three']

dump()和load()方法都会抛出pickle.PickleError,因此需要进行捕获。

这样保持list的方式,可以不使用print(list,fiie=’man.txt’)的方式,而使用

pickle.dump(list,‘man.txt’)的方式。

 

The str() BIFcan be used to access the stringed representation of any data object thatsupports the conversion.

 The locals() BIF returns a collection of variables within the current scope.

5. Comprehendingdata

strip()方法类似于Java的String中的trim()方法。

Sort in one of two ways

Python有两种方式排序:

1.In-place sorting takes your data, arrangesit in the order you specify, and then replaces your original datawith the sorted version.The original ordering is lost.With lists, the sort() method provides in-place sorting:

2.Copiedsorting takes your data, arranges it in the order you specify, and then returnsa sorted copy of your original data. Your original data’s ordering is maintained and onlythe copy is sorted. In Python, the sorted() BIF supports copied sorting.

By default, both the sort() method and thesorted() BIF order your data in ascending order. To order your data indescending order, pass the reverse=True argumentto either sort() or sorted()  and Pythonwill take care of things for you.

Comprehending lists

Consider whatyou need to do when you transform one list into another. Four things have tohappen. You need to:

1. Create a new list to hold thetransformed data.

2. Iterate each data item in the originallist.

3. With each iteration, perform thetransformation.

4. Append the transformed data to the newlist.

例如,mikey是一个list,现在把mikey中的元素经过sanitizer函数处理后,放入到clean_mikey中,使用如下:

clean_mikey = []

 for each_t in mikey:

     clean_mikey.append(sanitize(each_t))

Python还有更简洁的方式,只用一行代码,如下:

clean_mikey = [sanitize(each_t) for each_t in mikey]

比如meter是一个圆半径的list,计算周长

Cycle  = [m * 3.14 for m in meter]

Remove duplicates

list和Java中的List类似,是运行重复的,要删除list中重复元素,可以进行遍历,然后删除重复的如下:

unique_james = []

for each_t in james:

    if each_t not in unique_james:

        unique_james.append(each_t)

可以对list进行切片,如取出0到3(不包括)的元素,the_list[0:3]

或者使用set来删除重复,如:

>>> distances = {10.6, 11, 8, 10.6, "two", 7}

>>> distances = set(distances)

>>> print(distances)

{8, 7, 11, 'two', 10.6}

6. Custom dataobject

假设文件内容如下:

SarahSweeney,2002-6-17,2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55,2:22,2-21,2.22

第一个逗号前为姓名,第二个为生日,后面为时间,找出这人跑的最快的成绩:

def sanitize(time_string):

    if '-' in time_string:

        splitter = '-'

    elif ':' in time_string:

        splitter = ':'

    else:

        return(time_string)

    (mins, secs) = time_string.split(splitter)

    return(mins + '.' + secs)

 

def get_coach_data(filename):

    try:

        with open(filename) as f:

            data = f.readline()

        return(data.strip().split(','))

    except IOError as ioerr:

        print('File error: ' + str(ioerr))

        return(None)

   

sarah = get_coach_data('sarah2.txt')

 

(sarah_name, sarah_dob) = sarah.pop(0), sarah.pop(0)

 

print(sarah_name + "'s fastest times are: " +

        str(sorted(set([sanitize(t) for t in sarah]))[0:3]))

Use a dictionary to associate data

Dictionary类似于Java中的Map,提供键值对方式存储数据。创建dictionary方式:

>>> cleesee = {}

>>> type(cleesee)

<class 'dict'>

>>>

>>> palin = dict()

>>> type(palin)

<class 'dict'>

元素可以在初始化的时候添加,也可以直接添加:

>>> cleese['Name'] = 'John Cleese'

>>> cleese['Occupations'] = ['actor', 'comedian', 'writer', 'film producer']

>>> palin = {'Name': 'Michael Palin', 'Occupations': ['comedian', 'actor', 'writer', 'tv']}

和list不一样,dictionary是没有顺序的,即存储的顺序和插入时顺序并不一致。

Bundle your code and its data in a class

Like themajority of other modern programming languages, Python lets you create anddefine an object-oriented class that can be used to associate code with thedata that it operates on.

Python uses class to create objects. Every defined class has aspecial method called  __init__() , which allows you to control how objectsare initialized:

class Athlete:

  def __init__(self):

    # The code to initialize a "Athlete" object.

创建类的对象实例:

a = Athlete()

将会调用__init__方法:

Athlete().__init__(a)

In fact, notonly does the __init__()  method require self as its first argument, but so does every other method defined within your class

Python arrangesfor the first argument of every method to be the invoking (or calling) objectinstance. Let’s extend thesample class to store a value in a object attribute called thing with the valueset during initialization. Another method, called how_big(), returns the lengthof thing due to the use of the len() BIF:

class Athlete:

  def __init__(self, value=0):

    self.thing = value

  def how_big(self):

    return(len(self.thing))

下面是个例子:

>>> class Athlete:

       def __init__(self, name, dob = None, times=[]):

              self.name = name

              self.dob = dob

              self.times = times

 

>>> sarah = Athlete('Sarah Seeney', '2012-10-12', ['2:58', '2.58', '1.56'])

>>> james = Athlete('James Jones')

>>>

>>> type(sarah)

<class '__main__.Athlete'>

>>> type(james)

<class '__main__.Athlete'>

>>>

>>> sarah

<__main__.Athlete object at 0x01056770>

>>> sarah.name

'Sarah Seeney'

>>> james.name

'James Jones'

类定义后,属性可以动态添加,但是不能对没有的属性进行访问:

>>> sarah.hh

Traceback (most recent call last):

  File "<pyshell#50>", line 1, in <module>

    sarah.hh

AttributeError: 'Athlete' object has no attribute 'hh'

>>> sarah.hh = 'hh'

>>> sarah.hh

'hh'

Inherit from Python’s built-in list

Python中的类也可以继承build-in类,也可以继承自定义的类。

>>> class NamedList(list):

  def __init__(self, a_name):

    list.__init__([])

    self.name = a_name

   

>>> johnny = NamedList("John Paul Jones")

>>> type(johnny)

<class '__main__.NamedList'>

>>> dir(johnny)

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'append', 'count', 'extend', 'index', 'insert', 'name', 'pop', 'remove', 'reverse', 'sort']

>>> johnny.append("Bass Player")

>>> johnny.extend(['Composer', "Arranger", "Musician"])

>>> johnny

['Bass Player', 'Composer', 'Arranger', 'Musician']

>>> johnny.name

'John Paul Jones'

>>> for attr in johnny:

       print(johnny.name + ' is a ' + attr)

 

John Paul Jones is a Bass Player

John Paul Jones is a Composer

John Paul Jones is a Arranger

John Paul Jones is a Musician

Python supportmultiple inheritance。

if you save yourAthleteList class to a file called athletelist.py, you can import the into your codeusing this line of code:

from athletelist import AthleteList

7. webdevelopment

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值