python函数参考手册_python参考手册--第1章python简介

1.if __name__ == '__main__':

直接运行myModel.py时,当前模块的名字是main;import myModel然后运行的时候当前模块的名字是myModel。

2.eval: eval 函数的功能是将字符串生成语句并执行。

3.from module import class/func

module对应*.py文件,里面可以有class、func。class下还可以有func

4.利用set去重:links = [link for link in set(links)]

5.利用正则表达式匹配之后,根据组名取出值:

(?P\d+)是一个分组,item_count是组名

ret = re.search(r'count:\'(?P\d+)\'', html)

item_count = 0 if not ret else int(ret.group('item_count'))

6.python3,print作为函数使用:print("hello")

7.特殊变量_用于保存最后一次运算的结果

>>>600+100

700

>>>_+200

900

8.格式化输出:

print "%3d %0.2f" %(year,b)

print (format(year,"%3d"),format(b,"%0.2f"))

print "{0:3d} {1:0.2f}".format(year,b) #冒号前面的数字表示传递给format()方法的参数

9:python没有switch、case语句,使用多个if elif else 语句代替

10.for语句:for i in xrange(0,10)

11.按行读文件:

for line in open("foo.txt"):

print line

print写文件:

f = open("foo.txt",w)

while year<=nmyears:

principal = principal * (1 + rate)

print >>f,"%3d %0.2f" % (year,principal)

year +=1

f.close()

python3中不能使用>>,用下面代替:

print ("%3d %0.2f" % (year,principal),file = f)

write写文件:

f.write("%3d %0.2f\n" % (year,principal))

12.逻辑与、或、非:使用and、or、not

if a < 10 and a > :

print a

if b < 10 or b > 20:

print b

if not c

print c

13. utf8、gbk编码

>>> c=unicode('taobao_cocobella_35651013881_黑色','gbk').encode('utf8')

>>> c

'taobao_cocobella_35651013881_\xe9\xbb\x91\xe8\x89\xb2'

14.list、tuple、set、dict

list:可以增删,下标索引,连接。列表由于长度不固定,可增删,因此创建时会额外分配内存。

>>> a = [1,2,3,4,5]

>>> type(a)

>>> a[2]

3

>>> len(a)

5

>>> b = []

>>> c = list()

>>> b.append(a)

>>> b

[[1, 2, 3, 4, 5]]

tuple:不能增删,可以下标检索,连接,可以解包成变量,sql查询返回的就是tuple。元组由于长度固定,因此创建时分配内存就是这么大,不会额外分配。

>>> a =1,2,3,4

>>> a

(1, 2, 3, 4)

>>> type(a)

>>> b = ("hello",)

>>> b

('hello',)

>>> b[0]

'hello'

>>> studentInfo = ('Jack',24,'China')

>>> name,age,country = studentInfo

>>> name

'Jack'

>>> age

24

>>> country

'China'

>>> d = b + studentInfo

>>> d

('hello', 'Jack', 24, 'China')

可以list与tuple合起来用:

>>>students = []

>>> students.append(studentInfo)

>>> Hanmeimei = ('Hanmeimei',23,'USA')

>>> students.append(Hanmeimei)

>>> students

[('Jack', 24, 'China'), ('Jack', 24, 'China'), ('Hanmeimei', 23, 'USA')]

set:集合是无序的,可以用于去重,但是不能进行下标索引。支持并集、交集、差集、对称差集等。用add增加一项,update增加多项

>>> a = set()

>>> b = set([1,2,3,4,5])

>>> type(b)

>>> c = set([3,4,5,9,10,11])

>>> a = b | c

>>> d = b & c

>>> e = b - c

>>> f = b ^ c

>>> g = [a,d,e,f]

>>> g

[set([1, 2, 3, 4, 5, 9, 10, 11]), set([3, 4, 5]), set([1, 2]), set([1, 2, 9, 10, 11])]

>>> c.update([110,120,130])

>>> c

set([130, 3, 4, 5, 9, 10, 11, 110, 120])

>>> c.add(99)

>>> c

set([130, 3, 4, 5, 9, 10, 11, 110, 99, 120])

dict:字典,散列表。

>>> a = dict()

>>> b = {'name':'Jack','age':24,'country':'China'}

>>> b

{'country': 'China', 'age': 24, 'name': 'Jack'}

>>> b['name']

'Jack'

15.range、xrange

python3中xrange完全替换了python2中的range,统一成了range

在python2中,range(1000) 会立刻填满数据0,1,2。。。999

而xrange(1000)不会立刻填满,根据需要填值,省内存些。

16.生成器

使用yield的函数都是生成器,使用func.next()生成结果序列

>>> def func(n):

print 'Count down func. n = %s' % n

while n > 0:

yield n

n -=1

>>> count = func(10)

>>> count.next()

Count down func. n = 10

10

>>> count.next()

9

>>> for i in func(10):

print i

Count down func. n = 10

10

9

8

7

6

5

4

3

2

1

17.协程

使用(yield)创建协程,将输入参数作为一组任务,从而能处理一切发送过来的输入:

>>> def print_matches(matchText):

print "looking for",matchText

while True:

line = (yield)

if matchText in line:

print line

>>> matcher = print_matches('China')

>>> matcher.next()

looking for China

>>> matcher.send('fajsodfjaosidjfwodkfichafa asofjaofjwoijfoajsdf')

>>> matcher.send('I borned in China')

I borned in China

>>> matcher.close()

17.对象与类

dir()函数列出对象的所有可用方法,是交互试验的有用工具。

>>> dir(matcher)

['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'next', 'send', 'throw']

>>> dir(dict())

['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']

>>> dir(set())

['__and__', '__class__', '__cmp__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']

>>> dir(list())

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

>>> dir((1,2,3,4))

['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

类的派生:

class Student(Person):

def __init__(self,sname):#构造函数

self.name = sname

def getName()

return self.name

@staticmethod

def studentNum()

pass

18.异常处理

(1)try except语句

try:

func()

excetp:

print "error!"

(2)raise手动抛异常

func(n):

if n < 0:

raise valueError("n < 0")

这样调用func的地方就可以通过try捕获异常

(3)with语句

import threading

message_lock = threading .Lock()

...

with message_lock:

message.add(newMessage)

with语句自动获取message_lock对象,当执行离开with代码块后(即message.add(newMessage)),后面的对象message_lock自动释放。无论with语句内部是否发生异常都将会释放该message_lock。有点类似于java中的finally语句。

19.模块

module.py文件作为一个模块,模块里面可以有class、普通方法(区别于类成员函数)

(1)import module #导入模块

(2)from module import funcOrClass #导入模块中的方法及类

(3)import module as otherModuleName #使用别名导入模块

20.帮助信息

(1)help

>>> help(set)

Help on class set in module __builtin__:

class set(object)

| set() -> new empty set object

| set(iterable) -> new set object

|

| Build an unordered collection of unique elements.

|

| Methods defined here:

|

| __and__(...)

| x.__and__(y) <==> x&y

|

| __cmp__(...)

| x.__cmp__(y) <==> cmp(x,y)

|

| __contains__(...)

| x.__contains__(y) <==> y in x.

|

| __eq__(...)

| x.__eq__(y) <==> x==y

。。。

(2)__doc__

>>> print list.__doc__

list() -> new empty list

list(iterable) -> new list initialized from iterable's items

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python is an extensible, interpreted, object-oriented programming language. It supports a wide range of applica- tions, from simple text processing scripts to interactive Web browsers. Python 是一种可扩展的, 即译式, 面向对象规格的编程语言. 它能应用在极广泛的地方, 从简单的文字处理 工作到交互式的网页浏览器. While the Python Reference Manual describes the exact syntax and semantics of the language, it does not describe the standard library that is distributed with the language, and which greatly enhances its immediate usability. This library contains built-in modules (written in C) that provide access to system functionality such as file I/O that would otherwise be inaccessible to Python programmers, as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming. Some of these modules are explicitly designed to encourage and enhance the portability of Python programs. Python 语言参考手册 中精确地描述了Python 语言的句法及语义. 然而语言参考手册中没有提到Python 所 附带功能强大的标准库. 这个函式库大大地增强了Python 的实用性. 其中包括C 写的内建模组, 提供介面 让程式进行操作系统层次的工作, 例如档案的输出输入; 同时也有以Python 语言本身编写的模组, 为实际 编程时常遇的问题提供标准解决方案. 这类模组有的经过特别设计以便Python 程式在跨平台的情况下运 行无误. This library reference manual documents Python’s standard library, as well as many optional library modules (which may or may not be available, depending on whether the underlying platform supports them and on the configuration choices made at compile time). It also documents the standard types of the language and its built-in functions and exceptions, many of which are not or incompletely documented in the Reference Manual. 本参考手册罗列并说明了Python 标准库的各种功能, 以及许多非核心的模组(按不同的操作系统和编译时 的设置而定, 不是每台机上的Python 都能用这些模组.) 本手册同时记载了Python 语言所有的标准数据类 型, 内建函数, 异常类, 这些在参考手册中被忽略了或只是扼要的提过一下. This manual assumes basic knowledge about the Python language. For an informal introduction to Python, see the Python Tutorial; the Python Reference Manual remains the highest authority on syntactic and semantic questions. Finally, the manual entitled Extending and Embedding the Python Interpreter describes how to add new extensions to Python and how to embed it in other applications. 本手册的读者要对Python 有基本的认识. 初学者应该从Python 指南 开始. 至于Python 语言参考手册 则是该语言的语法和语义问题上的权威阐释. 最后 扩展或嵌入 Python 解释器 一文解说了如何在Python 中加入新的扩展模组; 以及怎样把Python 解释器嵌入到其他的应用程式中.

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值