python学习笔记

来源:互联网 发布:淘宝标题组词 编辑:程序博客网 时间:2024/05/21 10:00

1.print输出不换行,末尾用逗号

print "hello",

有时候需要强制print马上输出,可以用flush函数,需要导入sys模块

import sysprint "hello"sys.stdout.flush()

2.单元素元组,需要在元素后边加逗号,要不然会被当作普通的常量

t = ("hello",)

3.浅拷贝和深拷贝

浅拷贝只拷贝父对象,父对象内部的子对象不拷贝

深拷贝完全拷贝,包括父对象内部的子对象


4.python中的for循环,使用不当时,会产生bug,python官方文档中对此有以下说明:

Note There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.,

for x in a[:]:    if x < 0: a.remove(x)

用与a相等的临时对象来遍历元素,然后实际删除的是a中的元素,而a[:]没有变化


5.python类的成员变量无需事先在类定义中声明,使用时直接引用即可

以下是python文档中的描述

data attributes correspond to “instance variables” in Smalltalk, and to “data members” in C++. Data attributes need not be declared; like local variables, they spring into existence when they are first assigned to

class my:def __init__(self, real, image):self.r = realself.i = imagex = my(1, 2)x.counter = 2print "%d" % x.counter

6.python没有do while语句,可以用下面的while和if来实现同样的逻辑

while True:        stuff()        if fail_condition:                break


7.用命令pydoc查看python的帮助文档,可以直接以模块名当作参数

pydoc re   查看正则表达式模块的帮助文档pydoc sys  查看sys模块的帮助文档

还可以在浏览器里面查看文档,指定端口号后,pydoc会启动一个web服务器,把文档内容以网页的形式提供给用户,访问127.0.0.1:8000即可查看

pydoc -p 8000


8,for循环中,python自动把变量的个数和后边的list等元组匹配

import itertools, collectionsm = [[1,2], [3,4], [5,6], [7,8]]for i in m:print ifor i, j in m:print i, j
输出如下:

[1, 2]
[3, 4]
[5, 6]
[7, 8]
1 2
3 4
5 6
7 8


10.python中,程序退出可以用exit函数,需要先导入sys模块

import syssys.exit()

11.注意正则表达式模块中match和findall两个函数的不同

match只匹配开头的字符,清晰的定义pattern很重要!!!


12.区别import sth.和from sth. import sth.

import sth.导入一个模块,那么这个模块中的所有东西(类,外部变量,外部函数等)在引用的时候要加上模块名字,即sth.

from sth. import sth.,把某个模块中的某些项目(类,外部变量,外部函数等)导入该文件,那么这些项目就可以直接用名字引用,无需再加模块名,因为我们已经说明了把什么东西导入到这个文件中


比如,下面这些定义可以保存为文件mylibrary.py

class myclass():        def classfunction():                print "I'm class function"        classdata = "I'm class data"outdata = "I'm outer data"def outerfunction():        print "I'm outerfunction"

然后采用不同的方式导入

[user1@zion Documents]$ python
Python 2.7.5 (default, Nov 12 2013, 16:45:58)
[GCC 4.8.2 20131017 (Red Hat 4.8.2-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mylibrary
>>> import mylibrary.myclass
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named myclass
>>> from mylibrary import myclass
>>> from mylibrary import outdata
>>> from mylibrary import outerfunction
>>> from mylibrary import classdata
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name classdata
>>>

13.在函数中,可以直接引用全局变量,但是不能直接更改全局变量

下边是官方文档对此的描述

The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the global symbol table, and then in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.

count = 0 def func():        print "%d" % countprint "%d" % countfunc()print "%d" % count

从上边的例子可以发现,函数中可以直接访问外部全局变量。
在引用变量时,python遵循下面的查找顺序,首先在局部符号表中查找(即当前函数体中),然后在全局符号表中查找(即函数外部),然后是build-in符号表

count = 0 #1def func():        count = 1 #2        print "%d" % count #3print "%d" % countfunc()print "%d" % count

上边的小例子#1处定义了全局变量count,然后在#2处,函数func中,重新对count赋值,实际上#2处的count是在函数func中新定义的局部变量。按照python变量名查找规则,函数体中只能访问#2处的局部count,外部的count依然为0
如果要改变全局变量的值,需要用global声明,如下边的例子

count = 0 def func():        global count        count = 1        print "%d" % countprint "%d" % countfunc()print "%d" % count

用global声明后,count=1就起到了作用,成功修改了全局变量count
需要注意的是,下边的写法是错误的

count = 0def func():        count += 1        print "%d" % countprint "%d" % countfunc()print "%d" % count

python把函数中的count当作局部变量,那么明显这个局部变量无法自己给自己赋值,写成count = count + 1也是不行的,道理一样


14.注意下面这样的语句

"string1" + ",string2" if 2 > 1 else ""
该语句的执行结果为"string1,string2"

"string1" + ",string2" if 2 < 1 else ""

这个语句的执行结果为“”,空字符串

由此,我们知道python把if前边的东西当作一个整体


15.python解释器中添加自动补全

首先在/etc/bashrc文件中添加

export PYTHONSTARTUP="/home/user/.pythonrc"

上面的命令定义了一个环境变量,python解释器在启动的时候会读取PYTHONSTARTUP变量,执行这个变量指向的文件,一般把这个文件放到自己的家目录下,然后在.pythonrc文件中,写入下面的内容

import rlcompleter, readlinereadline.parse_and_bind("tab: complete")

即导入readline和自动补全的库

再用下面的命令使/etc/bashrc文件中的内容生效

source /etc/bashrc

然后,就可以用tab自动补全了

16.str.join()和str.split()这两个方法,需要注意的是他们的操作对象都是迭代器,并且迭代器返回的是字符串

'\n'.join(i for i in range(8))

上面的写法是错误的,因为i是int型,而join的参数需要为字符串迭代器,需要改为下面的写法

'\n'.join(str(i) for i in range(8))

即把i转换为字符串型的对象

下面的写法都是可以的

'\n'.join(i for i in ['a','b','c','d','e'])   '\n'.join(i for i in ('a','b','c','d','e'))   '\n'.join(i for i in {'a','b','c','d','e'})   

17.PyCharm,Idle中都会使用中文字符时,经常会遇到下面的错误

SyntaxError: Non-ASCII character 

此时,要在源文件的第一行声明文件编码,格式如下
# -*- coding: utf-8 -*- 
或者下面的格式

#coding=utf-8

下面是PEP对文件编码的规定,里面列出了几种常见的错误写法

http://legacy.python.org/dev/peps/pep-0263/

如果不对文件声明编码格式的话,python解释器默认为ASCII编码


18.需要注意下面的写法

m = (i for i in range(8))

m是一个生成器

19.当前路径下的模块可以直接导入

要导入某个文件夹下的模块,实际上就是导入package,首先要满足的一点是在文件夹下要有__init__.py文件,只有存在这个文件,python解释器才会把文件夹当作package对待,如果要导入的模块在某个很深的路径下,那么这个路径中的所有文件夹中都要有__init__.py文件。

很重要的一点,用from语句既可以导入文件夹,也可以导入文件(模块)。如果我们导入文件或者文件中的某个函数(类,变量都可以),那么可以直接引用。但是如果import一个文件夹(该文件夹下边一定要有__init__.py文件),那么该文件夹中的__init__.py文件就会被执行,这是理解import导入的关键。如果__init__.py为空文件,那么这样导入一个文件夹是没有任何意义的,因为没有任何有用的模块被导入,常用的方法是在__init__.py文件中用import写入要导入的模块。实际上这个文件就相当于控制哪些模块被导入。









                                             
0 0