Python学习

Python学习(一)

  主要是学习《Dive into Python


一、下载安装
最新版本:<st1:chsdate month="12" islunardate="False" day="30" year="1899" w:st="on" isrocdate="False">2.3.2</st1:chsdate>
Windows
  下载 Python-2.3.2.exe,运行安装

其它平台
  下载 Python-<st1:chsdate month="12" islunardate="False" day="30" year="1899" w:st="on" isrocdate="False">2.3.2</st1:chsdate>.tgz Python-2.3.2.tar.bz2,
  tar -zxvf Python-2.3.2.tgz bzcat Python-2.3.2.tar.bz2 | tar -xf -
  ./configure
  make
  make install
二、语法
1
、函数声明
关键字 def 为函数声明的开始,不区分有返回值的函数与无返回值的函数。它没有子程序,全部都是函数。
函数没有定义返回的数据类型。如果函数执行了一个 return 语句,它将返回一个值,否则会返回 None (Python的空值)
参数 params 并不需要指明数据类型

2、文档字符串
任何在三重双引号中的东西都是函数的文档字符串,它们用来说明函数可以做什么。
如果存在文档字符串,它必须要在函数中的被首先定义(也就是说在冒号后面被定义)
文档字符串在运行时可作为函数的属性。

3、在Python中每个东西都是对象
并且几乎每个东西都有属性和方法。
所有的函数都有一个内置的属性 __doc__,它会返回在函数源代码中定义的文档字符串。

4、缩排代码
Python
函数没有明显的 begin end,或任何括号或大括号来标识函数开始结束。唯一的分隔是通过一个冒号(:)和代码本身的缩排来表示。
代码块(函数,if 语句,for 循环,等等)通过它们的缩排来定义。缩排表示块的开始,非缩排表示结束,不存在明显的括号,大括号,或关键字。这就意味着空白是有意义的,并且要一致。

5if __name__
if 表达式周围不需要小括号
C语言一样,Python使用 == 进行比较,使用 = 进行赋值。
模块是对象,并且所有的模块都有一个内置属性 __name__。如果 import 模块,那么 __name__ 的值通常为模块的文件名,不带路径或者文件扩展名。如果直接运行模块, __name__ 的值将是一个特别的缺省值, __main__
通过在程序中加入下一个if,就可以很简单地实现单元测试。
if __name__ == "__main__":

6、字典
Python
的内置数据类型之一是字典,它在关键字与值之间定义了一对一的关系。这一点就象Perl中的关联数组,Java中的 Map ,或VBScipt中的 Scripting.Dictionary 对象。如:
>>> d = {"server":"mpilgrim", "database":"master"}
1)
每一个元素都是一个键-值对,整个元素集合用大括号括起来,赋值给变量d.
2)server
是一个键字,它所关联的值为 mpilgrim,用 d["server"] 来引用.
3)
你可以通过键字来得到值,但是不能通过值得到键字。
>>> d["database"] = "pubs"
4)
可如上式一样修改字典.
5)
不能在一个字典中有重复的键字。给一个存在的键字赋值会抹掉原来的值。
6)
可以在任何时候加入新的键-值对。这种语法同修改存在的值一样。
7)
字典没有元素顺序的概念。
8)
字典的值可以是任意数据类型,包括字符串,整数,对象,或者甚至其它的字典。
9)
字典的关键字要严格一些,但是它们可以是字符串,整数和几种其它的类型
>>> del d['server']
10)
可如上式一样删除元素
>>> d.clear()
11)
可如上式一样清空所有元素

7、列表
1)
个列表是一个用方括号包括的有序元素集。
>>> li = ["a", "b", "mpilgrim", "z", "example"]
2)
可如上式定义列表
3)
一个列表可以象一个以0开始的数组一样使用。任何一个非空列表的第一个元素总是 xxx[0]
4)
负数索引从列表的尾部开始向后计数存取元素。li[n] == li[n – len(li)],如:
>>> li[-3]
结果为"mpilgrim"
5)
任何一个非空的列表最后一个元素总是 li[-1]
6)
你可以通过指定2个索引得到列表的子集,叫做一个分片。返回值是一个新的列表,它包含了列表中按顺序从第一个分片索引开始,直到但是不包括第二个分片索引的所有元素。
7)
如果一个或两个分片索引是负数,分片也可以工作,但如果两个索引的所代表的位置大者在前则返回空列表。
8)
如果任一个分片索引为0,你可以将其省略,默认为0。所以li[:3]li[0:3] 一样。
9)li[:n]
将总是返回前 n 个元素,而 li[n:] 将返回其它的元素。
10)
如果两个分片索引均省略,将包括列表的所有元素。但是与原始的列表 li 不是同一个,它是一个新的列表,恰好拥有与 li 全部一样的元素。li[:] 是生成一个列表拷贝的缩写。
11)append
增加单个元素到列表的尾部。如:
>>> li.append("new")
12)insert
在列表中插入单个元素。数值参数是使得列表增加的第一个元素的索引(注意,不是序号).如下:
>>> li.insert(2, "new")
13)
列表元素不需要唯一
14)
extend 连接列表。注意不要用多个参数调用 extend ,要使用一个列表参数调用。如下:
>>> li.extend(["two", "elements"])
15)index
在列表中查找值第一次的出现并返回索引值
>>> li.index("example")
16)
如果在列表中没有找到值,Python会引发一个异常
17)
要测试一个值是否在列表内,使用 in,如果值找到了,它返回 1 ,或者没找到则为 0 (Python中不存在布尔类型。在一个布尔上下文中( if 语句)0 是假,所有其它的数值为真。这一点也可以扩展到其它类型。一个空串(""),一个空列表([]),和一个空字典({})都是假,所有其它的字符串,列表,和字典是真。)如:
>>> "new" in li
18)remove
从列表中除掉第一次出现的值。(仅第一次出现的值),如:
>>> li.remove("new")
19)
如果在列表中没有找到值,Python引发一个异常。它反映了 index 方法的行为。
20)
pop除掉列表的最后一个元素,然后返回除掉的值。注意这一点同 li[-1]不同,后者返回一个值但不改变列表,也不同于 li.remove(value),后者改变列表但不返回值。如:
>>> li.pop()
21)
列表也可以用 + 操作符连接起来。list = list + otherlist 相当于 list.extend(otherlist)。但是 + 操作符将连接后的列表作为一个值返回,而 extend 仅修改存在的列表。如:
>>> li = li + ['example', 'new']
22)Python
支持 += 操作符。li += ['two'] 相当于 li = li + ['two']+= 操作符可用于列表,字符串,和整数,并且它也可以在用户定义类中被重载。
23)*
操作符作为一个重复符可用在列表上。li = [1, 2] * 3 相当于 li = [1, 2] + [1, 2] + [1, 2], 将三个列表连成一个。

8、序列
1)
序列是不可变列表。一旦创建了一个序列就不能以任何方式改变它。
2)
序列的定义同列表的定义方式相同,除了整个元素集是用小括号包围的而不是方括号
3)
当分割一个列表时,会得到一个新的列表;当分割一个序列时,会得到一个新的序列。
4)
序列没有方法,所以不能查找、删除和增加元素,但可以用in来检查元素是否在序列里。
5)
序列比列表操作速度快。
6)
序列可以在字典中被用作关键字,但是列表不行。
7)
内置的 tuple 函数接收一个列表,返回一个有着相同元素的序列。而 list 函数接收一个序列,返回一个列表。从效果上看,tuple 冻结一个列表,而 list 解冻一个序列。
8)
序列用在字符串格式化.
9
、变量
1)Python
象大多数其它语言一样有局部和全局变量,但是它没有明显的变量声明。变量通过赋值产生,当超出作用范围时自动消灭。
2)
当一条命令用续行符(“\”)分割成多行时,后续的行可以以任何方式缩排,Python通常的严格的缩排规则不需遵守。
3)
严格地讲,在小括号,方括号或大括号中的表达式(如定义字典)可以用或者不用续行符(“\”)分割成多行。
4)Python
不允许你引用一个未被赋值的变量,试图这样做会引发一个异常。

10、字符串格式化
1)
基本语法如下:
"
带占位符的字符串" % (参数序列)
2)
试图将一个字符串同一个非字符串连接会引发一个异常。字符串连接只能在每个都是字符串时起作用。此时选择格式化串会是个不错的主意。

11、映射
1)
基本语法如下:
[
函数或表达式 for 循环变量 in 列表/序列 ]
2)
映射是通过循环遍历一个列表/序列,并对每个元素应用一个函数,然后返回一个包含为计算后的值的新列表。
3)
注意列表映射不改变被映射的列表。
4)
新列表拥有与原有列表/序列拥有相同数量的元素数。

Python学习(二)<o:p></o:p>

  今天继续dive into python.<o:p></o:p>

12、列表与字符串
  1)用一个字符串对象的join 方法将列表元素连接成单个字符串,此字符串充当分隔符。
  2)join 只用用于字符串列表;它不进行任何的类型强制转换。连接一个存在一个或多个非字符串元素的列表将引发一个异常。
  3)用一个字符串对象的split 方法将列表元素连接成单个字符串,此字符串充当分隔符。
  4)split 接受一个可选的第二个参数,它是要分割的次数。
  5)split 无参数调用时,默认为以空白为分隔符(空格/换行/制表符),多个连续空白初见为一个。<o:p></o:p>

13、导入模块
  1)Python用两种方法导入模块,一是import module,一种是from module import,
  2)第一种方法导入整个模块,对其属性或方法的引用要加限制名,如:
>>> import types
>>> types.FunctionType
  3)第二种方法将模块的方法和属性直接导入名字空间中,可以直接引用这些方法和属性,如:
>>> from types import FunctionType
>>> FunctionType
  4)两种方法各有利弊,前者可明确指定要导入的方法和属性,并直接引用,比较方便;对于属性或方法重名的情况,则后者非常有用。<o:p></o:p>

14、函数的参数
  1)函数的参数可以拥有缺省值,某个参数有什么缺省值在定义函数时指明,
  2)拥有缺省值的参数为可选参数,否则为必备参数,即调用函数时必须为必备参数提供参数,如果没有对可选参数提供参数值,则其使用缺省值。
  3)调用函数时,可以通过指定参数名而以任意次序来传递参数,称为定名参数。如:
定义:
def help(object, spacing=10, collapse=1):
合法调用:
help(odbchelper)
help(odbchelper, 12)
help(odbchelper, collapse=0)
help(spacing=15, object=odbchelper)
  4)参数是个字典,缺省可以不指定名字而用顺序将参数名与值匹配起来。<o:p></o:p>

15、内置函数
  1)所有Python内置函数被组合进一个名叫 __builtins__ (前后有两个下划线)的特别模块中。
  2)内置函数dir 返回任意一个对象的属性和方法的列表。
  3)内置函数str 强制将任一种类型的数据转化为字符串,对python的空值None,则str(None)返回字符串"None”.
  4)内置函数type 返回任意对象的数据类型。
  5)使用函数 getattr 得到对象的各种引用,这个过程中方法没有被调用。
  
  6)使用getattr得到引用后,其返回值为方法,可以调用相应的函数。如下:
>>>getattr(li, "append")("Moe")
  
16
、列表映射过滤语法
[mapping-expression for element in source-list if filter-expression]<o:p></o:p>

17and-or技巧,bool and a or b来说,
  1)逻辑运行采用了快捷方式,即如果or前值为真,是不再计算后面的值,并返回前面的结果
  2) (bool and [a] or [b])[0]的方法,可以实现与cbool?a:b的功能<o:p></o:p>

18lambda函数
  1)可以使用lambda定义单行的最小函数,格式如下:
funcVar = lambda x : x...
  没有名字,返回是默认的。上式中可以没有funcVar,有funcVar时可与正常函数一样调用,没有funcVar时可如下调用:
(lambda x:x...)(a)
  2)lambda函数可以接受一到多个参数(包括可选参数),返回单个表达式的值,函数中不能包含命令,表达式不能超过一个。<o:p></o:p>

19、一些小技巧
  1)python几乎总是在操作列表
  2)字符串的ljust(spacing)可以在右边加空格以达到spacing值所示的长度,当spacing的值小于字符串的长度时,不会截断。<o:p></o:p>

:builtin的属性表<o:p></o:p>

属性<o:p></o:p>

说明<o:p></o:p>

ArithmeticError<o:p></o:p>

Base class for arithmetic errors.<o:p></o:p>

AssertionError <o:p></o:p>

Assertion failed.<o:p></o:p>

AttributeError <o:p></o:p>

Attribute not found.<o:p></o:p>

DeprecationWarning <o:p></o:p>

Base class for warnings about deprecated features.<o:p></o:p>

EOFError <o:p></o:p>

Read beyond end of file.<o:p></o:p>

EnvironmentError <o:p></o:p>

Base class for I/O related errors.<o:p></o:p>

Exception<o:p></o:p>

Common base class for all exceptions.<o:p></o:p>

FloatingPointError <o:p></o:p>

Floating point operation failed.<o:p></o:p>

FutureWarning<o:p></o:p>

Base class for warnings about constructs that will change semantically in the future.<o:p></o:p>

IOError<o:p></o:p>

I/O operation failed.<o:p></o:p>

ImportError<o:p></o:p>

Import can't find module, or can't find name in module.<o:p></o:p>

IndentationError <o:p></o:p>

Improper indentation.<o:p></o:p>

IndexError <o:p></o:p>

Sequence index out of range.<o:p></o:p>

KeyError <o:p></o:p>

Mapping key not found.<o:p></o:p>

KeyboardInterrupt<o:p></o:p>

Program interrupted by user.<o:p></o:p>

LookupError<o:p></o:p>

Base class for lookup errors.<o:p></o:p>

MemoryError<o:p></o:p>

Out of memory.<o:p></o:p>

NameError<o:p></o:p>

Name not found globally.<o:p></o:p>

NotImplementedError<o:p></o:p>

Method or function hasn't been implemented yet.<o:p></o:p>

OSError<o:p></o:p>

OS system call failed.<o:p></o:p>

OverflowError<o:p></o:p>

Result too large to be represented.<o:p></o:p>

OverflowWarning<o:p></o:p>

Base class for warnings about numeric overflow.<o:p></o:p>

PendingDeprecationWarning <o:p></o:p>

Base class for warnings about features which will be deprecated in the future.<o:p></o:p>

ReferenceError <o:p></o:p>

Weak ref proxy used after referent went away.<o:p></o:p>

RuntimeError <o:p></o:p>

Unspecified run-time error.<o:p></o:p>

RuntimeWarning <o:p></o:p>

Base class for warnings about dubious runtime behavior.<o:p></o:p>

StandardError<o:p></o:p>

Base class for all standard Python exceptions.<o:p></o:p>

StopIteration<o:p></o:p>

Signal the end from iterator.next().<o:p></o:p>

SyntaxError<o:p></o:p>

Invalid syntax.<o:p></o:p>

SyntaxWarning<o:p></o:p>

Base class for warnings about dubious syntax.<o:p></o:p>

SystemError<o:p></o:p>

Internal error in the Python interpreter. Please report this to the Python maintainer, along with the traceback, the Python version, and the hardware/OS platform and version.<o:p></o:p>

SystemExit <o:p></o:p>

Request to exit from the interpreter.<o:p></o:p>

TabError <o:p></o:p>

Improper mixture of spaces and tabs.<o:p></o:p>

TypeError<o:p></o:p>

Inappropriate argument type.<o:p></o:p>

UnboundLocalError<o:p></o:p>

Local name referenced but not bound to a value.<o:p></o:p>

UnicodeDecodeError <o:p></o:p>

Unicode decoding error.<o:p></o:p>

UnicodeEncodeError <o:p></o:p>

Unicode encoding error.<o:p></o:p>

UnicodeError <o:p></o:p>

Unicode related error.<o:p></o:p>

UnicodeTranslateError<o:p></o:p>

Unicode translation error.<o:p></o:p>

UserWarning<o:p></o:p>

Base class for warnings generated by user code.<o:p></o:p>

ValueError <o:p></o:p>

Inappropriate argument value (of correct type).<o:p></o:p>

Warning<o:p></o:p>

Base class for warning categories.<o:p></o:p>

WindowsError <o:p></o:p>

MS-Windows OS system call failed.<o:p></o:p>

ZeroDivisionError<o:p></o:p>

Second argument to a division or modulo operation was zero.<o:p></o:p>


builtin
方法(函数)<o:p></o:p>

方法<o:p></o:p>

说明<o:p></o:p>

__import__ <o:p></o:p>

__import__(name, globals, locals, fromlist) -> module Import a module. The globals are only used to determine the context; they are not modified. The locals are currently unused. The fromlist should be a list of names to emulate ``from name import ...'', or an empty list to emulate ``import name''. When importing a module from a package, note that __import__('A.B', ...) returns package A when fromlist is empty, but its submodule B when fromlist is not empty.<o:p></o:p>

abs<o:p></o:p>

abs(number) -> number Return the absolute value of the argument.<o:p></o:p>

apply<o:p></o:p>

apply(object[, args[, kwargs]]) -> value Call a callable object with positional arguments taken from the tuple args, and keyword arguments taken from the optional dictionary kwargs. Note that classes are callable, as are instances with a __call__() method. Deprecated since release 2.3. Instead, use the extended call syntax: function(*args, **keywords).<o:p></o:p>

callable <o:p></o:p>

callable(object) -> bool Return whether the object is callable (i.e., some kind of function). Note that classes are callable, as are instances with a __call__() method.<o:p></o:p>

chr<o:p></o:p>

chr(i) -> character Return a string of one character with ordinal i; 0 <= i < 256.<o:p></o:p>

cmp<o:p></o:p>

cmp(x, y) -> integer Return negative if x<y, zero if x==y, positive if x>y.<o:p></o:p>

coerce <o:p></o:p>

coerce(x, y) -> None or (x1, y1) When x and y can be coerced to values of the same type, return a tuple containing the coerced values. When they can't be coerced, return None.<o:p></o:p>

compile<o:p></o:p>

compile(source, filename, mode[, flags[, dont_inherit]]) -> code object Compile the source string (a Python module, statement or expression) into a code object that can be executed by the exec statement or eval(). The filename will be used for run-time error messages. The mode must be 'exec' to compile a module, 'single' to compile a single (interactive) statement, or 'eval' to compile an expression. The flags argument, if present, controls which future statements influence the compilation of the code. The dont_inherit argument, if non-zero, stops the compilation inheriting the effects of any future statements in effect in the code calling compile; if absent or zero these statements do influence the compilation, in addition to any features explicitly specified.<o:p></o:p>

delattr<o:p></o:p>

delattr(object, name) Delete a named attribute on an object; delattr(x, 'y') is equivalent to ``<st1:place w:st="on"><st1:state w:st="on">del</st1:state></st1:place> x.y''.<o:p></o:p>

dir<o:p></o:p>

dir([object]) -> list of strings Return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it: No argument: the names in the current scope. Module object: the module attributes. Type or class object: its attributes, and recursively the attributes of its bases. Otherwise: its attributes, its class's attributes, and recursively the attributes of its class's base classes.<o:p></o:p>

divmod <o:p></o:p>

divmod(x, y) -> (div, mod) Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.<o:p></o:p>

eval <o:p></o:p>

eval(source[, globals[, locals]]) -> value Evaluate the source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals and locals are dictionaries, defaulting to the current globals and locals. If only globals is given, locals defaults to it.<o:p></o:p>

execfile <o:p></o:p>

execfile(filename[, globals[, locals]]) Read and execute a Python script from a file. The globals and locals are dictionaries, defaulting to the current globals and locals. If only globals is given, locals defaults to it.<o:p></o:p>

filter <o:p></o:p>

filter(function or None, sequence) -> list, tuple, or string Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list.<o:p></o:p>

getattr<o:p></o:p>

getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case.<o:p></o:p>

globals<o:p></o:p>

globals() -> dictionary Return the dictionary containing the current scope's global variables.<o:p></o:p>

hasattr<o:p></o:p>

hasattr(object, name) -> bool Return whether the object has an attribute with the given name. (This is done by calling getattr(object, name) and catching exceptions.)<o:p></o:p>

hash <o:p></o:p>

hash(object) -> integer Return a hash value for the object. Two objects with the same value have the same hash value. The reverse is not necessarily true, but likely.<o:p></o:p>

hex<o:p></o:p>

hex(number) -> string Return the hexadecimal representation of an integer or long integer.<o:p></o:p>

id <o:p></o:p>

id(object) -> integer Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.)<o:p></o:p>

input<o:p></o:p>

input([prompt]) -> value Equivalent to eval(raw_input(prompt)).<o:p></o:p>

intern <o:p></o:p>

intern(string) -> string ``Intern'' the given string. This enters the string in the (global) table of interned strings whose purpose is to speed up dictionary lookups. Return the string itself or the previously interned string object with the same value.<o:p></o:p>

isinstance <o:p></o:p>

isinstance(object, class-or-type-or-tuple) -> bool Return whether an object is an instance of a class or of a subclass thereof. With a type as second argument, return whether that is the object's type. The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for isinstance(x, A) or isinstance(x, B) or ... (etc.).<o:p></o:p>

issubclass <o:p></o:p>

issubclass(C, B) -> bool Return whether class C is a subclass (i.e., a derived class) of class B. When using a tuple as the second argument

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值