Python随笔

1. Python的好处要在你用过其他语言写一大堆代码实现某个功能,然后惊奇地发现Python可以用更短更少的代码实现,那样你就会觉得Python好厉害。

有对比,才能体现Python的好处。

2.开发效率 VS 代码性能?    

当然不是二选一,学两种语言(动态+静态)来应对不同需求。

3. Python文件的开头

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

#!/usr/bin/python 告诉系统这个程序是用该路径下的名为python的程序来跑的

#coding=utf-8 表示文件基于utf-8编码,不写这个会默认用ascii编码,ascii不支持中文编码。所以如果要用中文编码,就需要加上这一行。

4.python format string

print 默认换行,可以设置separator, new line 。 如果想print不换行,则在print 之后加一个逗号,逗号后面为空,所以print函数认为不用 默认的new line参数

print "Hey %s there" % "you"    会打印Hey you there.像C的printf一样。

print '{} {}'.format('one', 'two')    占位符 placeholder

  好处,  可以调整占位符的位置     print '{1} {0}'.format(1, 2)   占位符下标从0开始
repr()函数, %r,  representation 这个函数打印raw data, 比较字符串打印出来如果有 就打印 ,   字符串会打印出引号标识,  backslash会打印两个 \

5. 语法糖

函数调用不会写 ()

变量定义: 不用写def,直接变量名和等于号

var = 1

负数下标

print '*' * 10   # 打印10次 *

a, b = 1, 2 可以这样赋值

w for w in [1, 2, 3]  循环赋值

6. 控制台输入

raw_input()       参数是提示信息

int( raw_input() ) 将输入强制转换为整数,   input()函数有安全风险

eval 函数, 将输入作为python表达式,对表达式求值。   可以将String转换为dict, list, tuple

  input 函数等效于 eval(raw_input())

7. Unix的Ctrl + D   等于Windows的 Ctrl + Z + Enter

8. 查看函数的API :  pydoc命令, 比如pydoc raw_input

9. 文件: 打开: open()  file() , 用open, 不用file()

txt = open("file_name")
txt.read()

Python可以多次打开一个文件

其它函数:close() read()

readline()读一行 truncate() 清空文件内容 write('something')写文件

10. from ... import ...

导入argv, from sys import argv

导入exists, from os.path import exists

11. 函数

def 函数名() :

  函数体

注意格式:def开头, ()之后又:冒号,函数体要缩进

返回值:groovy的返回值是最后一行的值,但Python默认返回None

12. 文档注释 document comments

  """  里面的内容就是文档注释 """

13. 导入自己写的脚本

  import xxxx

  xxxx为脚本名,不需要加上后缀 .py

import 引入包      :缺点,使用时要多大一点字,"包名. "

from 包 import 函数或常量  : 只引入具体的函数或常量

from 包 import *       : 引入包中的所有东西

14. 布尔值

<> 和 != 一个效果,但是,<>被弃用(deprecated)

操作符用:and not or

注意: 表达式"test" == "test", 返回"test", 而不是布尔值。

Why does "test" and "test" return "test" or 1 and 1 return 1 instead of True?
    Python and many languages like to return one of the operands to their boolean expressions rather than just True or False. 
This means that if you did False and 1 you get the first operand (False) but if you do True and 1 your get the second (1). Play with this a bit.

15. IF

people = 20
cats = 30
dogs = 15
if people < cats:
    print "Too many cats! The world is doomed!"

if 条件不用放在括号中

if 条件之后又 : 冒号

if 的执行代码要缩进

16. for-loop for循环

for i in range(0, 5):

  print "%d " % i

 i 需要定义吗?  不需要,每次for循环都会给i赋值,相当于初始化

range(0, 5) 只循环五次,最后一个元素不循环。range是左闭右开。

印象中python有类似 [0..5] 这样构造list的方法,但实际没有,也不知道为什么会有这个印象。

17. Debug建议

The best way to debug a program is to use print to print out the values of variables at points in the program to see where they go wrong.

不要用debugger。打印比debugger好。

18. KeyWord 关键字

as      Part of the with-as statement.   with X as Y: pass
assert  Assert (ensure) that something is true. assert False, "Error!"
def     Define a function. def X(): pass
del     Delete from dictionary. del X[Y]  从字典中删除
except  If an exception happens, do this. except ValueError, e: print e
exec    Run a string as Python. exec 'print "hello"'    执行Python表达式
global  Declare that you want a global variable. global X
is      Like == to test equality. 1 is 1 == True
lambda  Create a short anonymous function. s = lambda y: y ** y; s(3)  匿名函数
pass    This block is empty. def empty(): pass  空语句
raise   Raise an exception when things go wrong. raise ValueError("No")  抛异常,相当于Java的throw
with    With an expression as a variable do. with X as Y: pass   with是一个控制流语句,跟if/for/while/try之类的是一类的,with可以用来简化try finally代码,看起来可以比try finally更清晰。 
yield   Pause here and return to caller. def X(): yield Y; X().next()

 with expression as variable

  with block

 引入上下文管理协议(context management protocol),那些要处理上下文的代码可以用with。。。as来简化代码。 比如写文件,上文(setup。。。)是打开文件,下文(teardown)是关闭文件handler。

file = open("/tmp/foo.txt")
try:
    data = file.read()
finally:
    file.close()
with open("/tmp/foo.txt")
 as file:
    data = file.read()

理解Python的With as语句

yield: 暂停函数并返回值。

def fab(max):
    a,b = 0,1
    while a < max:
        yield a
        a, b = b, a+b

for i in fab(20):
print i,",",

yield计算出第一个Fibonacci数列后暂停,调用者可以输出该返回值,然后下一次调用fab()时,会从暂停处恢复,继续计算下一个值。

yield用于文件读取,还能节省内存。意思是不用整个大文件一次性读出来,读一点,返回一点,整个过程只占用固定的缓冲区。

关于Python中的yield

19. Python运算符 Operator

**  Power of
/   Division
//  Floor division

 20. join 函数

连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串+

语法:  'sep'.join(seq)

参数说明
sep:分隔符。可以为空
seq:要连接的元素序列、字符串、元组、字典
上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串

返回值:返回一个以分隔符sep连接各个元素后生成的字符串

Python中的join()函数的用法

21. xrange() 函数

range函数返回一个List,xrange不返回 List,而是返回一个 iterable 对象。

Iterable对象的好处是节省内存。

22.  Python如何解释函数

more_stuff.pop() reads as, "Call pop on more_stuff."

pop(more_stuff) means, "Call pop with argument more_stuff."

23. dict 字典

用{}符号

关键字和值都可以使任何类型,好吧,List不可以做关键字。

删除元素:用del关键字

  del stuff[1]

Python的字典的items(), keys(), values()都返回一个list

items函数 : 以列表返回可遍历的(键, 值) 元组数组。

24. Python的非操作是 not , 不是!

25. class Name(object) 加不加object的区别

不加(object) 会有更少的对象函数

26. composition over inheritance

  组合:定义很多接口

27.  项目结构  如何鼓捣一个Python项目:

先安装 pip (包管理)  distribute(软件分发) nose(测试)virtualenv(独立的Python运行环境)

egg(蟒蛇蛋,像.jar, 便于安装和部署)   wheel (用来替代egg)

mkdir projects
cd projects/
mkdir skeleton
cd skeleton/
mkdir bin NAME tests docs
touch NAME/__init__.py
touch tests/__init__.py

setup.py

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

config = {
    'description': 'My Project',
    'author': 'My Name',
    'url': 'URL to get it at.',
    'download_url': 'Where to download it.',
    'author_email': 'My email.',
    'version': '0.1',
    'install_requires': ['nose'],
    'packages': ['NAME'],
    'scripts': [],
    'name': 'projectname'
}

setup(**config)

/tests/NAME_tests.py

from nose.tools import *
import NAME

def setup():
    print "SETUP!"

def teardown():
    print "TEAR DOWN!"

def test_basic():
    print "I RAN!"

项目结构

skeleton/
     NAME/
         __init__.py
     bin/
     docs/
     setup.py
     tests/
         NAME_tests.py
         __init__.py

 建立好项目的结构后,在skeleton目录下执行nosetests命令,它会找所有.test文件执行。 (assert或raise assertionError表示test失败)

28. pip distribute 等工具的关系

(busted 被捕的)

可以看到distribute是setuptools的替代方案,pip是easy_install的替代方案。

Distribute提供一个安装python模块的框架。你系统的每一个python解释器都需要它自己的Distribute。

29. Web Framework Web框架

lpthw.web 框架 , 和web.py很像?。  但这个更好

原文地址:https://www.cnblogs.com/longwaytogo/p/6917527.html