python学习记录

1.print

>>> print 'The quick brown fox', 'jumps over', 'the lazy dog'
The quick brown fox jumps over the lazy dog
逗号分割字符串,空格输出

2.raw_input

name = raw_input('please enter your name: ')
print 'hello,',name
标准输入,注意输入得到的都是字符串

3.#表示注释

4.大小写敏感

5.基础数据类型:整数,浮点数,字符串,布尔值,空值

整数:100,-100,0,0xf

浮点数:3.14,3.14e10,3.14e-10

>>> print 3.14e10
31400000000.0
字符串:以"或者'包含的任意文本,\表示转义,r'字符转'表示不转义

>>> print '\\\t\\'
\	\
>>> print r'\\\t\\'
\\\t\\
'''...'''表示多行

>>> print '''line1
line2
line3'''
line1
line2
line3
布尔值:True,False. 可以使用and ,or, not 运算

>>> print True and False
False
空值:None,一个特殊的值

6.变量,弱类型,直接赋值

a = 'ABC'
b = a
a = 'XYZ'
print b
ABC
a指向创建的字符串,b与a指向同一个字符串,a指向另外一个字符串,b不变

7.常量,PI=3.14,一般用大写表示,实际上PI还是个变量

>>> print 10/3
3
>>> print 10.0/3
3.33333333333
8.编码

>>> ord('A')
65
>>> chr(65)
'A'
u'...'表示unicode编码


#!/usr/bin/env python
# -*- coding: utf-8 -*-
第二行注释表示使用utf8编码,中文注意

9.格式化

%d 整数
%f 浮点数
%s 字符串
%x 十六进制整数

>>> 'Hello, %s' % 'world'
'Hello, world'
>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'
多个参数的时候,用括号,一个不需要

指定格式什么的

>>> '%2d-%02d' % (3, 1)
' 3-01'
>>> '%.2f' % 3.1415926
'3.14'
10.列表list,元组tuple,字典dict, 及set

list []中括号,可以添加删除修改等

list的几个方法,append,insert,pop

>>> classmates = ['Michael', 'Bob', 'Tracy']
>>> classmates
['Michael', 'Bob', 'Tracy']
>>> len(classmates)
3
>>> classmates[1]
'Bob'
>>> classmates[-1]
'Tracy'
>>> classmates.append('Adam')
>>> classmates
['Michael', 'Bob', 'Tracy', 'Adam']
>>> classmates.insert(1, 'Jack')
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']
>>> classmates.pop()
'Adam'
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy']
>>> classmates.pop(1)
'Jack'
>>> classmates
['Michael', 'Bob', 'Tracy']
>>> classmates[1] = 'Sarah'
>>> classmates
['Michael', 'Sarah', 'Tracy']

list之间可以互相嵌套,也可以是不同的元素,也可以是空的

>>> L = ['Apple', 123, True]
>>> L
['Apple', 123, True]
>>> s = ['python', 'java', ['asp', 'php'], 'scheme']
>>> len(s)
4
>>> s[2][1]
'php'
>>> L = []
>>> len(L)
0
tuple ()小括号,初始化以后不能修改,没有append,insert方法,获取方法一致
>>> t = (1, 2)
>>> t
(1, 2)
>>> t = ()
>>> t
()
>>> t = (1,)
>>> t
(1,)
定义只有一个元素的元组要加逗号,避免与运算中的括号产生歧义

dict {}花括号,字典,key-value形式

>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95
>>> d['Adam'] = 67
>>> d
{'Bob': 75, 'Michael': 95, 'Tracy': 85, 'Adam': 67}
>>> d['Jack'] = 90
>>> d
{'Jack': 90, 'Bob': 75, 'Michael': 95, 'Tracy': 85, 'Adam': 67}
>>> d.pop('Bob')
75
>>> d
{'Jack': 90, 'Michael': 95, 'Tracy': 85, 'Adam': 67}
>>> print d.get('Thomas')
None
>>> d.get('Thomas', -1)
-1
>>> d.get('Jack', -1)
90
>>> 'Thomas' in d
False
key是一个固定值,get方法获取key的value值,获取不到报错,需要判断

dict另外一种表示方式

>>> a=dict(x=1,y=1)
>>> a
{'y': 1, 'x': 1}

set就是一个key的集合,没有value值,set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作

>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
set([2, 3])
>>> s1 | s2
set([1, 2, 3, 4])
不能理解有啥用,先不管了。

11.条件判断与循环

<strong>if条件判断</strong>,不多说了。注意py是按照缩进来执行的
age = 20
if age >= 6:
    print 'teenager'
elif age >= 18:
    print 'adult'
else:
    print 'kid'

for的循环

names = ['Michael', 'Bob', 'Tracy']
for name in names:
    print name
for x in xxx循环输出

>>> range(5)
[0, 1, 2, 3, 4]
产生一个序列
sum = 0
for x in range(101):
    sum = sum + x
print sum

while语句

sum = 0
n = 99
while n > 0:
    sum = sum + n
    n = n - 2
print sum


12.函数

</pre><strong>内置的一些函数</strong></p><p>abs(-20) 绝对值</p><p>cmp(2,1)比较大小</p><p>类型转换函数</p><p><pre name="code" class="python">>>> int('123')
123
>>> int(12.34)
12
>>> float('12.34')
12.34
>>> str(1.23)
'1.23'
>>> unicode(100)
u'100'
>>> bool(1)
True
>>> bool('')
False
函数指针什么的

>>> a = abs
>>> a(-1)
1
函数定义
def my_abs(x):
    if x >= 0:
        return x
    else:
        return -x


一个空的函数

def nop():
    pass
pass用来做占位,可以不报错


返回多值

import math

def move(x, y, step, angle=0):
    nx = x + step * math.cos(angle)
    ny = y - step * math.sin(angle)
    return nx, ny
>>> x, y = move(100, 100, 60, math.pi / 6)
>>> print x, y
151.961524227 70.0
>>> print move(100, 100, 60, math.pi / 6)
(151.96152422706632, 70.0)
多只的返回其实是一个元组,在语法上,返回一个tuple可以省略括号,而多个变量可以同时接收一个tuple,按位置赋给对应的值


函数参数

默认参数

def power(x, n=2):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s
默认参数一定要用不可变对象,如果是可变对象,运行会有逻辑错误!


*args是可变参数,args接收的是一个tuple
**kw是关键字参数,kw接收的是一个dict。 这两个先放着先。看上去有点意思,实际应用未知。


13.高级特性

切片

>>> L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
>>> L[0:3]
['Michael', 'Sarah', 'Tracy']
>>> L
['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
>>> L[:3]
['Michael', 'Sarah', 'Tracy']
>>> L = range(5)
>>> L
[0, 1, 2, 3, 4]
>>> L[:3]
[0, 1, 2]
>>> L = range(100)
>>> L[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> L[-10:]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> L[:10:2]
[0, 2, 4, 6, 8]
>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
>>> (0, 1, 2, 3, 4, 5)[:3]
(0, 1, 2)
>>> 'ABCDEFG'[::2]
'ACEG'
迭代 for ...in 

>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
	print key

a
c
b
默认情况下,dict迭代的是key。如果要迭代value,可以用for value in d.itervalues(),如果要同时迭代key和value,可以用for k, v in d.iteritems()。
>>> for ch in 'ABC':
	print ch

A
B
C
如果需要索引,按下面方式

>>> for i, value in enumerate(['A', 'B', 'C']):
	print i, value
0 A
1 B
2 C
列表生成式

列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。

>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
还可以加判断条件去生成

>>> [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]
两层的

>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
变量的

>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.iteritems()]
['y=B', 'x=A', 'z=C']
变小写的列子

>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']
判断类型

>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str)
True
>>> isinstance(y, str)
False

生成器
自定义的生成器函数中包含 yield,遇到就返回,暂时不知道咋用,不管先。



14.函数式编程
逼格太高,先无视了。


15.模块

一个.py文件就称之为一个模块(Module),按包路径来命名a/b/c.py,模块名字就是 a.b.c,注意c.py下面要有一个__init__.py,这个本身也是一个模块,对应的模块就是a.b

例子

#!/usr/bin/env python
# -*- coding: utf-8 -*-

' a test module '

__author__ = 'Michael Liao'

import sys

def test():
    args = sys.argv
    if len(args)==1:
        print 'Hello, world!'
    elif len(args)==2:
        print 'Hello, %s!' % args[1]
    else:
        print 'Too many arguments!'

if __name__=='__main__':
    test()
前面是一些列注释,加作者,导入包,定义函数

运行模块的时候,解释器会定义__name__=__main__那么就会执行test,从其他地方导入的时候就不会定义,所以这个可以用来测试本模块,但是其他导入的时候就不会运行。
模块别名

try:
    import json # python >= 2.6
except ImportError:
    import simplejson as json # python <= 2.5
作用为兼容

作用域
一般的为public,比如变量abc,PI等,私有一般定义为_开头,_private,__开头和结尾__的一般有特殊作用,就不要使用了。这只是约定的,不是强制。

第三方模块安装

easy_install PIL
或者pip什么的。一般还是看文档吧。

包的搜索路径定义在sys.path

>>> import sys
>>> sys.path
['', '/Library/Python/2.7/site-packages/pycrypto-2.6.1-py2.7-macosx-10.9-intel.egg', '/Library/Python/2.7/site-packages/PIL-1.1.7-py2.7-macosx-10.9-intel.egg', ...]

16.面向对象
类的定义

class Student(object):

    def __init__(self, name, score):
        self.name = name
        self.score = score

object是父类对象,一般不知道就用object类。__init__方法是初始化方法,self不需要传递。

实例化

>>> bart = Student('Bart Simpson', 59)
>>> lisa=Student('Lisa Simpson', 87)
>>> bart.age = 8
>>> bart.age
8
>>> lisa.age
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'age'
实例化之后的对象可以自己添加属性,两个对象的属性也可以不一样。


类的私有变量,用__开头就不能直接访问,实际上变成了_Student__name

继承和多态

与C++概念类似,无视吧。

获取对象信息
type()

isinstance()

dir()    获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list

应该是ORM之类的反射机制可以用到吧。暂时不管,应该没有那么高级的应用吧。


@property 装饰器啥的,跟java好像

定制类 重写一些方法满足要求

元类 类似模板元变成生成类什么的,太牛逼,无视先。


17.异常机制

try...except...finally...
try:
    print 'try...'
    r = 10 / int('a')
    print 'result:', r
except ValueError, e:
    print 'ValueError:', e
except ZeroDivisionError, e:
    print 'ZeroDivisionError:', e
else:
    print 'no error!'
finally:
    print 'finally...'
print 'END'
logging模块记录异常信息,这应该也不会用到很多吧,不管了。

18.I/O操作

try:
    f = open('/path/to/file', 'r')
    print f.read()
finally:
    if f:
        f.close()
等价于

with open('/path/to/file', 'r') as f:
    print f.read()
read()  一次性全部读取

read(size) 读取size个字节

readlines() 读取所有行

for line in f.readlines():
    print(line.strip()) # 把末尾的'\n'删掉

二进制文件读取

open标志位设置为rb

字符编码读取

import codecs
with codecs.open('/Users/michael/gbk.txt', 'r', 'gbk') as f:
    f.read() # u'\u6d4b\u8bd5'

写文件操作
>>> f = open('/Users/michael/test.txt', 'w')
>>> f.write('Hello, world!')
>>> f.close()
等价于

with open('/Users/michael/test.txt', 'w') as f:
    f.write('Hello, world!')
with会自动调用close

系统变量

>>> os.name  #操作系统
'nt'
>>> os.uname #具体版本 linux的
>>> os.environ #环境变量
>>> os.getenv('PATH')
'D:\\Tcl\\bin;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\system32\\wbem;D:\\Qt\\4.8.6\\bin;d:\\Nmap;D:\\JRE\\bin;D:\\Python27;D:\\Python27\\Scripts'

目录操作
# 查看当前目录的绝对路径:
>>> os.path.abspath('.')
'/Users/michael'
# 在某个目录下创建一个新目录,
# 首先把新目录的完整路径表示出来:
>>> os.path.join('/Users/michael', 'testdir')
'/Users/michael/testdir'
# 然后创建一个目录:
>>> os.mkdir('/Users/michael/testdir')
# 删掉一个目录:
>>> os.rmdir('/Users/michael/testdir')
把两个路径合成一个时,不要直接拼字符串,而要通过os.path.join()函数,这样可以正确处理不同操作系统的路径分隔符。同样拆分也不能直接拆分,使用split函数拆分得到最后一级目录或者文件名
>>> os.path.split('/Users/michael/testdir/file.txt')
('/Users/michael/testdir', 'file.txt')
splittext()直接得到后缀

>>> os.path.splitext('/path/to/file.txt')
('/path/to/file', '.txt')
# 对文件重命名:
>>> os.rename('test.txt', 'test.py')
# 删掉文件:
>>> os.remove('test.py')
拷贝文件没有实现,使用shutil模块提供了copyfile()的函数

http://wangwei007.blog.51cto.com/68019/1106818---例子吧

两个例子

#列出当前目录下的所有目录,只需要一行代码
>>> [x for x in os.listdir('.') if os.path.isdir(x)]
['.lein', '.local', '.m2', '.npm', '.ssh', '.Trash', '.vim', 'Adlm', 'Applications', 'Desktop', ...]
#要列出所有的.py文件,也只需一行代码:
>>> [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']
['apis.py', 'config.py', 'models.py', 'pymonitor.py', 'test_db.py', 'urls.py', 'wsgiapp.py']


序列化

可以序列化到文件或者json格式,暂时用不到,配置文件什么的应该可以用到


19.进程与线程

多进程

跨平台使用multiprocessing模块,进程间通信是通过Queue、Pipes等实现的,可以方便的实现分布式多进程,这个可以研究一下。

多线程

import time, threading

# 新线程执行的代码:
def loop():
    print 'thread %s is running...' % threading.current_thread().name
    time.sleep(1)
    print 'thread %s ended.' % threading.current_thread().name

print 'thread %s is running...' % threading.current_thread().name

for i in range(10):
    t = threading.Thread(target=loop)
    t.start()
    #t.join() #等待线程结束

print 'thread %s ended.' % threading.current_thread().name

Python解释器由于设计时有GIL全局锁,导致了多线程无法利用多核。多线程的并发在Python中就是一个美丽的梦。虽然达不到100%利用。


ThreadLocal 其实就是TLS啦,线程的全局存储区域吧。

ThreadLocal最常用的地方就是为每个线程绑定一个数据库连接,HTTP请求,用户身份信息等,这样一个线程的所有调用到的处理函数都可以非常方便地访问这些资源。

import threading

# 创建全局ThreadLocal对象:
local_school = threading.local()

def process_student():
    print 'Hello, %s (in %s)' % (local_school.student, threading.current_thread().name)

def process_thread(name):
    # 绑定ThreadLocal的student:
    local_school.student = name
    process_student()

t1 = threading.Thread(target= process_thread, args=('Alice',), name='Thread-A')
t2 = threading.Thread(target= process_thread, args=('Bob',), name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join()
每个线程绑定不影响

也可以让一个类继承threading.local,那么这个类中的变量对于每个线程都特有存在。

20.正则表达式
这个就另外开个帖子讲吧,应该比较多,以后好好用





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值