Python快速介绍 ::-- ZoomQuiet [DateTime(2007-03-22T12:02:49Z)]

Include(CPUGnav) TableOfContents

1. s5

1.1. 演示备案

备课,经典Pythonic 代码以支持展示

1.1.1. iPython

  • dir()

  • help()

1.1.2. 高级数据类型

Include(PyPrimeNumberGenerator)

In [1]: li = range(10)

In [2]: li
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [3]: li[6]
Out[3]: 6

In [4]: li[:6]
Out[4]: [0, 1, 2, 3, 4, 5]

In [5]: li[6:]
Out[5]: [6, 7, 8, 9]

In [6]: li[:-6]
Out[6]: [0, 1, 2, 3]

In [7]: li[-6:]
Out[7]: [4, 5, 6, 7, 8, 9]

In [8]: li[::3]
Out[8]: [0, 3, 6, 9]

In [9]: li[:6:3]
Out[9]: [0, 3]

In [10]: li[6::3]
Out[10]: [6, 9]

In [11]: li[3:9:3]
Out[11]: [3, 6]

In [12]: li[3:9]
Out[12]: [3, 4, 5, 6, 7, 8]

1.1.2.1. 乘法表

In [13]: for i in range(1,10,1): [ i*j for j in range(1,i) ]
   ....:
Out[13]: []
Out[13]: [2]
Out[13]: [3, 6]
Out[13]: [4, 8, 12]
Out[13]: [5, 10, 15, 20]
Out[13]: [6, 12, 18, 24, 30]
Out[13]: [7, 14, 21, 28, 35, 42]
Out[13]: [8, 16, 24, 32, 40, 48, 56]
Out[13]: [9, 18, 27, 36, 45, 54, 63, 72]

1.1.2.2. 单行素数生成器!

  • 展示思路...

    In [154]: a=7
    In [156]: [d for d in range(2,a-1)]
    Out[156]: [2, 3, 4, 5]
    In [155]: [a%d for d in range(2,a-1)]
    Out[155]: [1, 1, 3, 2]
    
    In [162]: a=8
    In [163]: 0 not in [a%d for d in range(2,a-1)]
    Out[163]: False
    
    In [167]: N=10
    In [168]: [p for p in range(2,N) if  0 not in [p%d for d in range(2,p-1)]]
    Out[168]: [2, 3, 5, 7]

Include(PyPrimeNumberGenerator)

1.1.3. 函式参数

{{{工厂模式... In [174]: def doit(do,i,j):

  • ....: done = "%s %s %s" % (i,do,j)
  • ....: print "want do::",done
  • ....: return eval(done)

In [125]: def myfun(*args):

In [139]: def myfun(**kvar):

In [140]: myfun(k1=12,k2=23) {'k2': 23, 'k1': 12} {'k2': 25, 'k1': 14} }}}

1.1.4. OOP

  • 重载运算符+

    In [15]: class nplus:
       ....:     def __init__(self,one):
       ....:         self.one = one
       ....:     def __add__(self,two):
       ....:         return self.one*two
    
    In [16]: a=nplus(10)
    
    In [17]: a+2
    Out[17]: 20

1.1.4.1. 自省!

In [19]: def reprself(item):
   ....:     print "ID   :",id(item)
   ....:     print "TYPE :",type(item)
   ....:     print "VALUE:",repr(item)
   ....:     if hasattr(item,"__name__"):
   ....:         print "NAME::",item.__name__
   ....:     if hasattr(item,"__calss__"):
   ....:         print "CLASS::",item.__calss__.__name__

In [20]: reprself(reprself)
ID   : -1212717100
TYPE : <type 'function'>
VALUE: <function reprself at 0xb7b767d4>
NAME:: reprself

In [21]: reprself(123)
ID   : 136453144
TYPE : <type 'int'>
VALUE: 123

In [22]: reprself("123")
ID   : -1212647168
TYPE : <type 'str'>
VALUE: '123'

In [23]: reprself([1,2,3])
ID   : -1212664436
TYPE : <type 'list'>
VALUE: [1, 2, 3]

In [24]: reprself((1,2,3))
ID   : -1212700676
TYPE : <type 'tuple'>
VALUE: (1, 2, 3)

In [25]: reprself({1:"1","2":2,3:[3,]})
ID   : -1212705004
TYPE : <type 'dict'>
VALUE: {3: [3], 1: '1', '2': 2}
  • 追溯谁父辈:

{{{import traceback In [200]: def callme():

  • ....: s = traceback.extract_stack()
  • ....: print "i'd call by %s !" % s[-2][2]

In [201]: fun1() i'd call by fun1 ! }}}

  • 谁调用了俺?

参考下面的例子:
[A.py]
import B

[C.py]
import B

[B.py]
def who_import_me():
    import sys
    frame = sys._getframe()
    importer_name = frame.f_back.f_back.f_code.co_filename
    return importer_name[:-3]
   
print 'Hi module %s' % who_import_me()   

运行结果:
D:\Python Program\import>python A.py
Hi module A

D:\Python Program\import>python C.py
Hi module C

1.1.4.2. Mixin-混入!

In [202]: class A:
   .....:     def __init__(self):
   .....:         self.name = "class A"
   .....:     def do(self):
   .....:         print self.name

In [203]: class B:
   .....:     def __init__(self):
   .....:         self.name = "class B"
   .....:     def add(self,a,b):
   .....:         return a+b
In [212]: A.__bases__ +=(B,)

In [213]: A.
A.__doc__     A.__init__    A.__module__  A.add         A.do

1.1.4.3. Plugin

def p2(self,*arg):print "in %s !!!! %s"%(self.name,arg)
setattr(A,"plugin",p2)

1.1.5. 对象序列化

In [234]: lis=[1,2,"as",[1,2],(2,3,3),{}]
In [235]: pickle.dump(lis,open("lisA.dump","w"))

In [237]: li2 = pickle.load(open("lisA.dump"))
In [238]: li2
Out[238]: [1, 2, 'as', [1, 2], (2, 3, 3), {}]

1.1.6. 编译字节文件

def myfunc(alist):
    return len(alist)
the following command can be used to get the disassembly of myfunc():
import dis
>>> dis.dis(myfunc)
  2           0 LOAD_GLOBAL              0 (len)
              3 LOAD_FAST                0 (alist)
              6 CALL_FUNCTION            1
              9 RETURN_VALUE        
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE

1.2. 函式编程

map(func, list, …)
相当于[func(l) for l in list]
In [241]: map((lambda x:x*x),range(10))
Out[241]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [254]: map((lambda x,y:x+y),range(0,10,1),range(10,0,-1))
Out[254]: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]

In [257]: a=range(1,10,2)
In [258]: a
Out[258]: [1, 3, 5, 7, 9]

In [259]: b=range(10,0,-2)
In [260]: b
Out[260]: [10, 8, 6, 4, 2]

In [264]: zip(a,b)
Out[264]: [(1, 10), (3, 8), (5, 6), (7, 4), (9, 2)]

In [101]: [(lambda x,y : x+y)(i,j) for i,j in zip(a,b)]
Out[101]: [11, 11, 11, 11, 11]

In [102]: ["%s-%s "%(i,j) for i,j in zip(a,b)]
Out[102]: ['1-10 ', '3-8 ', '5-6 ', '7-4 ', '9-2 ']

1.2.1. 中蟒

Include(ChinesePython/tasting)

2. 反馈

PageComment2