1. _ builtin _ 模块

1.1 apply:使用元组或字典中的参数调用函数

Python 允许你实时地创建函数参数列表. 只要把所有的参数放入一个元组中,然后通过内建的 apply 函数调用函数.


In [8]:
def function(a,b):
    print a, b

In [9]:
apply(function, ("wheather", "Canada?"))


wheather Canada?

In [3]:
apply(function, (1, 3+5))


1 8

效果等同于:


In [4]:
function("wheather", "Canada?")


wheather Canada?

In [5]:
function(1, 3+5)


1 8

那为什么要使用apply呢?


In [10]:
apply(function, (), {"a":"35cm", "b":"12cm"})


35cm 12cm

In [16]:
apply(function, ("v",), {"b":"love"})


v love

In [21]:
apply(function, ( ,"v"), {"a":"hello"})


  File "<ipython-input-21-075685bc83e8>", line 1
    apply(function, ( ,"v"), {"a":"hello"})
                      ^
SyntaxError: invalid syntax

何谓“关键字参数”?

apply使用字典传递关键字参数,实际上就是字典的键是函数的参数名,字典的值是函数的实际参数值。(相对于形参和实参)

根据上面的例子看,如果部分传递,只能传递后面的关键字参数,不能传递前面的。????

apply 函数的一个常见用法是把构造函数参数从子类传递到基类, 尤其是构造函数需要接受很多参数的时候.

子类和基类是什么概念?


In [22]:
class Rectangle:
    def __init__(self, color="white", width=10, height=10):
        print "Create a ", color, self, "sized", width, "X", height

In [23]:
class RoundRectangle:
    def __init__(self, **kw):
        apply(Rectangle.__init__, (self,), kw)

In [24]:
rect = Rectangle(color="green", width=200, height=156)


Create a  green <__main__.Rectangle instance at 0x0000000003684E48> sized 200 X 156

In [34]:
rect = RoundRectangle(color="brown", width=20, height=15)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-34-799235dba81c> in <module>()
----> 1 rect = RoundRectangle(color="brown", width=20, height=15)

<ipython-input-23-ac7804c40e49> in __init__(self, **kw)
      1 class RoundRectangle:
      2     def __init__(self, **kw):
----> 3         apply(Rectangle.__init__, (self,), kw)

TypeError: unbound method __init__() must be called with Rectangle instance as first argument (got RoundRectangle instance instead)

第二个函数不知道如何使用 ????

修改,子类要以父类为参数!!!


In [41]:
class RoundRectangle(Rectangle):
    def __init__(self, **kw):
        apply(Rectangle.__init__, (self,), kw)

In [42]:
rect2 = RoundRectangle(color= "blue", width=23, height=10)


Create a  blue <__main__.RoundRectangle instance at 0x00000000036E4348> sized 23 X 10

使用 * 来标记元组, ** 来标记字典.

apply的第一个参数是函数名,第二个参数是元组,第三个参数是字典。所以用上面这个表达最好不过。


In [39]:
args = ("er",)
kwargs = {"b":"haha"}
function(*args, **kwargs)


er haha

In [40]:
apply(function, args, kwargs)


er haha

以上等价。

用这个意思引申:


In [44]:
kw = {"color":"brown", "width":123, "height": 34}
rect3 = RoundRectangle(**kw)


Create a  brown <__main__.RoundRectangle instance at 0x00000000036E1D88> sized 123 X 34

In [45]:
rect4 = Rectangle(**kw)


Create a  brown <__main__.Rectangle instance at 0x00000000036E1EC8> sized 123 X 34

In [46]:
arg=("yellow", 45, 23)
rect5 =  Rectangle(*arg)


Create a  yellow <__main__.Rectangle instance at 0x00000000036E1DC8> sized 45 X 23

1.2 import


In [47]:
import glob, os

In [48]:
modules =[]

In [49]:
for module_file in glob.glob("*-plugin.py"):
    try:
        module_name, ext = os.path.splitext(os.path.basename(module_file))
        module = __import__(module_name)
        modules.append(module)
    except ImportError:
        pass #ignore broken modules

In [56]:
for module in modules:
    module.hello()
example-plugin says hello


  File "<ipython-input-56-0755481c0a01>", line 3
    example-plugin says hello
                      ^
SyntaxError: invalid syntax

In [54]:
def hello():
    print "example-plugin says hello"

In [57]:
def getfunctionname(module_name, function_name):
    module = __import__(module_name)
    return getattr(module, function_name)

In [58]:
print repr(getfunctionname("dumbdbm","open"))


<function open at 0x00000000036A7DD8>

3. os模块


In [1]:
import os
import string

In [5]:
def replace(file, search_for, replace_with):
    back = os.path.splitext(file)[0] + ".bak"
    temp = os.path.splitext(file)[0] + ".tmp"
    
    try:
        os.remove(temp)
    except os.error:
        pass
    
    fi = open(file)
    fo = open(temp, "w")
    
    for s in fi.readlines():
        fo.write(string.replace(s, search_for, replace_with))
    
    fi.close()
    fo.close()
        
    try:
        os.remove(back)
    except os.error:
        pass
    
    os.rename(file, back)
    os.rename(temp, file)

In [2]:
file = "samples/sample.txt"

In [6]:
replace(file, "hello", "tjena")

In [7]:
replace(file, "tjena", "hello")

os.path.splitext:切扩展名

os.remove:remove a file。上面的程序里为什么要remove呢?


In [13]:
def replace1(file, search_for, replace_with):
    back = os.path.splitext(file)[0] + ".bak"
    temp = os.path.splitext(file)[0] + ".tmp"
    
    try:
        os.remove(temp)
    except os.error:
        pass
    
    fi = open(file)
    fo = open(temp, "w")
    
    for s in fi.readlines():
        fo.write(string.replace(s, search_for, replace_with))
        
    fi.close()
    fo.close()
    
    try:
        os.remove(back)
    except os.error:
        pass

    
    os.rename(file, back)
    os.rename(temp, file)

In [14]:
replace1(file, "hello", "tjena")

In [15]:
replace1(file, "tjena", "hello")

In [8]:
doc = os.path.splitext(file)[0] + ".doc"

In [16]:
for file in os.listdir("samples"):
    print file


sample.bak
sample.txt

In [17]:
cwd = os.getcwd()

In [18]:
print 1, cwd


1 I:\github\omooc2py\_src\exercise

In [19]:
os.chdir("samples")

In [20]:
print 2, os.getcwd()


2 I:\github\omooc2py\_src\exercise\samples

In [22]:
os.chdir(os.pardir)
print 3, os.getcwd()


3 I:\github\omooc2py\_src\exercise

In [ ]:

5. stat模块


In [53]:
import stat

In [55]:
import os, time

In [67]:
st = os.stat("samples/sample.txt")

os.stat是将文件的相关属性读出来,然后用stat模块来处理,处理方式有多重,就要看看stat提供了什么了。


In [ ]:

6. string模块


In [1]:
import string

In [60]:
text = "Monty Python's Flying Circus"

In [61]:
print "upper", "=>", string.upper(text)


upper => MONTY PYTHON'S FLYING CIRCUS

In [62]:
print "lower", "=>", string.lower(text)


lower => monty python's flying circus

In [63]:
print "split", "=>", string.split(text)


split => ['Monty', "Python's", 'Flying', 'Circus']

分列变成了list


In [64]:
print "join", "=>", string.join(string.split(text))


join => Monty Python's Flying Circus

join和split相反。


In [65]:
print "replace", "=>", string.replace(text, "Python", "Cplus")


replace => Monty Cplus's Flying Circus

replace的参数结构是:

  1. 整字符串 2. 将被替换的字符串 3. 替换后的字符串

In [66]:
print "find", "=>", string.find(text, "Python")


find => 6

In [67]:
print "find", "=>", string.find(text, "Python"), string.find(text, "Cplus")


find => 6 -1

In [68]:
print text


Monty Python's Flying Circus

上面replace的结果,没有影响原始的text。

find时,能找到就显示位置,不能找到就显示-1


In [70]:
print "count", "=>", string.count(text,"n")


 count => 3

和数学运算一样,这些方法也分一元的和多元的:

upper, lower, split, join 都是一元的。其中join的对象是一个list。

replace, find, count则需要除了text之外的参数。replace需要额外两个,用以指明替换关系。find只需要一个被查找对象。count则需要一个需要计数的字符。

特别注意: replace不影响原始字符串对象。(好奇怪)


In [2]:
print string.atoi("23")


23

In [3]:
type(string.atoi("23"))


Out[3]:
int

In [4]:
int("234")


Out[4]:
234

In [5]:
type(int("234"))


Out[5]:
int

In [6]:
type(float("334"))


Out[6]:
float

In [7]:
float("334")


Out[7]:
334.0

In [8]:
string.atof("456")


Out[8]:
456.0

7. re模块


In [48]:
import re

In [49]:
text = "The Attila the Hun Show"

In [52]:
m = re.match(".", text)
if m:
    print repr("."), "=>", repr(m.group(0))


'.' => 'T'

In [ ]:


In [ ]:


In [ ]:


In [ ]:

8. math模块和cmath模块


In [9]:
import math

In [10]:
math.pi


Out[10]:
3.141592653589793

In [11]:
math.e


Out[11]:
2.718281828459045

In [12]:
print math.hypot(3,4)


5.0

In [13]:
math.sqrt(25)


Out[13]:
5.0

In [14]:
import cmath

In [15]:
print cmath.sqrt(-1)


1j

10. operator模块


In [16]:
import operator

In [18]:
operator.add(3,5)


Out[18]:
8

In [19]:
seq = 1,5,7,9

In [22]:
reduce(operator.add,seq)


Out[22]:
22

In [23]:
reduce(operator.sub, seq)


Out[23]:
-20

In [24]:
reduce(operator.mul, seq)


Out[24]:
315

In [26]:
float(reduce(operator.div, seq))


Out[26]:
0.0

operator下的这四则运算,都是针对两个数进行的,即参数只能是两个。为了能对多个数进行连续运算,就需要用reduce,它的意思是两个运算后,作为一个数,与下一个继续进行两个数运算,直到数列终。感觉和apply作用有点差不多,第一个参数是函数,第二个参数是数列(具体参数)。


In [27]:
operator.concat("ert", "erui")


Out[27]:
'erterui'

In [28]:
operator.getitem(seq,1)


Out[28]:
5

In [29]:
operator.indexOf(seq, 5)


Out[29]:
1

getitem和indexOf为一对逆运算,前者求指定位置上的值,后者求给定值的位置。注意,后者是大写的字母o。


In [31]:
operator.sequenceIncludes(seq, 5)


Out[31]:
True

判断序列中是否包含某个值。结果是布尔值。


In [33]:
import UserList

In [39]:
def dump(data):
    print data,":"
    print type(data),"=>",
    if operator.isCallable(data):
        print "is a CALLABLE data."
    if operator.isMappingType(data):
        print "is a MAP data."
    if operator.isNumberType(data):
        print "is a NUMBER data."
    if operator.isSequenceType(data):
        print "is a SEQUENCE data."

In [40]:
dump(0)


0 :
<type 'int'> => is a NUMBER data.

In [41]:
dump([3,4,5,6])


[3, 4, 5, 6] :
<type 'list'> => is a SEQUENCE data.

In [42]:
dump("weioiuernj")


weioiuernj :
<type 'str'> => is a SEQUENCE data.

In [43]:
dump({"a":"155cm", "b":"187cm"})


{'a': '155cm', 'b': '187cm'} :
<type 'dict'> => is a MAP data.

In [44]:
dump(len)


<built-in function len> :
<type 'builtin_function_or_method'> => is a CALLABLE data.

In [45]:
dump(UserList)


<module 'UserList' from 'C:\Users\admin\Anaconda2\lib\UserList.pyc'> :
<type 'module'> =>

In [46]:
dump(UserList.UserList)


<class 'UserList.UserList'> :
<class 'abc.ABCMeta'> => is a CALLABLE data.

In [47]:
dump(UserList.UserList())


[] :
<class 'UserList.UserList'> => is a SEQUENCE data.

15. types模块


In [1]:
import types

In [4]:
def check(object):
    if type(object) is types.IntType:
        print "INTEGER",
    if type(object) is types.FloatType:
        print "FLOAT",
    if type(object) is types.StringType:
        print "STRING",
    if type(object) is types.ClassType:
        print "CLASS",
    if type(object) is types.InstanceType:
        print "INSTANCE",
    print

In [5]:
check(0)


INTEGER

In [6]:
check(0.0)


FLOAT

In [7]:
check("picklecai")


STRING

In [8]:
class A:
    pass

In [9]:
check(A)


CLASS

In [10]:
a = A()

In [11]:
check(a)


INSTANCE

types 模块在第一次引入的时候会破坏当前的异常状态. 也就是说, 不要在异常处理语句块中导入该模块 ( 或其他会导入它的模块 ) .


In [ ]:


In [ ]:

16. gc模块

gc 模块提供了到内建循环垃圾收集器的接口。


In [2]:
import gc

In [3]:
class Node:
    def __init__(self, name):
        self.name = name
        self.patrent = None
        self.children = []
        
    def addchild(self, node):
        node.parent = self
        self.children.append(node)
        
    def __repr__(self):
        return "<Node %s at %x" % (repr(self.name), id(self))
    
root = Node("monty")

root.addchild(Node("eric"))
root.addchild(Node("john"))
root.addchild(Node("michael"))

In [8]:
root.__init__("eric")

In [9]:
root.__repr__()


Out[9]:
"<Node 'eric' at 3737448"

In [ ]: