求知 文章 文库 Lib 视频 iPerson 课程 认证 咨询 工具 讲座 Modeler   Code  
会员   
 
  
 
 
     
   
分享到
python标准库学习(前篇)
 

作者 Rollen Holt,火龙果软件 发布于2013-12-23

 

使用字典或者元祖中的参数调用元素

def function( a, b ):
print a, b
apply( function, ( 1, 2 ) )
apply( function, ( 1 , ), {"b":2} ) #注意这里的","
apply( function, (), {"a":1, "b":2} )

apply 函数的一个常见用法是把构造函数参数从子类传递到

函数需要接受很多参数的时候.

class Rectangle: 
def __init__( self, color = "white", width = 10, height = 10 ):
print "create a", color, self, "sized", width, "x", height

class RoundedRectangle( Rectangle ):
def __init__( self, **kw ):
apply( Rectangle.__init__, ( self, ), kw )

rect = Rectangle( color = "green", height = 100, width = 100 )
rect = RoundedRectangle( color = "blue", height = 20 )

使用*a来表示元祖,**b来表示字典

def function1( *a, **b ):
print a, b
apply( function1, ( 1, 2 ) )
apply( function1, ( 1, ), {"b":2} )

动态导入所以已plugin结尾的模块

import glob, os 
modules = []

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
def hello():
print "hello"

for module in modules:
module.hello()

使用__import__导入特定的函数

def getfunctionbyname( module_name, function_name ):
module = __import__( module_name )
return getattr( module, function_name )

print repr( getfunctionbyname( "dumbdbm", "open" ) )

使用__import__延迟导入需要的模块,比如第一次使用的时候才导入

class LazyImport:
def __init__( self, moule_name ):
self.moule_name = moule_name
self.moule = None
def __getattr__( self, name ):
if self.moule is None:
self.moule = __import__( self.moule_name )
return getattr( self.moule, name )

string = LazyImport( "string" )
print string.lowercase

class A: 
def a( self ):
pass
def b( self ):
pass

class B( A ):
def c( self ):
pass
def d( self ):
pass

def getmembers( klass, members = None ):
# get a list of all class members, ordered by class
if members is None:
members = []
for k in klass.__bases__:
getmembers( k, members )
for m in dir( klass ):
if m not in members:
members.append( m )
return members
print getmembers( A )
print getmembers( B )
print getmembers( IOError )

列出指定目录中的所有文件:

import os
for file in os.listdir( "../src" ):
print file

获得,修改当前的目录

import os
# where are we?
cwd = os.getcwd()
print "1", cwd

# go down
os.chdir( "../" )
print "2", os.getcwd()

# go back up
os.chdir( os.pardir )
print "3", os.getcwd()

创建目录,删除目录

import os
fp = open( "../src/levels/file", "w" )
fp.write( "inspector praline" )
fp.close()
os.remove( "../src/levels/file" )
os.removedirs( "../src/levels" )

返回文件的信息:

import os
import time
file = "../src/hello.xml"
def dump( st ):
mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime = st
print "- size:", size, "bytes"
print "- owner:", uid, gid
print "- created:", time.ctime( ctime )
print "- last accessed:", time.ctime( atime )
print "- last modified:", time.ctime( mtime )
print "- mode:", oct( mode )
print "- inode/dev:", ino, dev
# get stats for a filename

st = os.stat( file )

print "stat", file
dump( st )
print

#
# get stats for an open file
fp = open( file )
st = os.fstat( fp.fileno() )
print "fstat", file
dump( st )

笔者的输出结果为:

stat ../src/hello.xml

- size: 274 bytes

- owner: 0 0

- created: Sun Aug 07 20:45:31 2011

- last accessed: Mon Aug 08 12:34:28 2011

- last modified: Mon Aug 08 12:34:28 2011

- mode: 0100666

- inode/dev: 0 0
fstat ../src/hello.xml

- size: 274 bytes

- owner: 0 0

- created: Sun Aug 07 20:45:31 2011

- last accessed: Mon Aug 08 12:34:28 2011

- last modified: Mon Aug 08 12:34:28 2011

- mode: 0100666

- inode/dev: 6192449487670266 0

输出为;using nt ...

using nt ...

split => ('my/little', 'pony')

splitext => ('my/little/pony', '')

dirname => my/little

basename => pony

join => my/little\pony

注意这里的 ``split`` 只分割出最后一项(不带斜杠).

import operator
sequence = 1, 2, 4
print "add", "=>", reduce(operator.add, sequence)
print "sub", "=>", reduce(operator.sub, sequence)
print "mul", "=>", reduce(operator.mul, sequence)
print "concat", "=>", operator.concat("spam", "egg")
print "repeat", "=>", operator.repeat("spam", 5)
print "getitem", "=>", operator.getitem(sequence, 2)
print "indexOf", "=>", operator.indexOf(sequence, 2)
print "sequenceIncludes", "=>", operator.sequenceIncludes(sequence, 3)

add => 7

sub => -5

mul => 8

concat => spamegg

repeat => spamspamspamspamspam

getitem => 4

indexOf => 1

sequenceIncludes => False

注意copy中的一些问题:

import copy

a = [[1], [2], [3]]
b = copy.copy( a )

print "before", "=>"
print a
print b

# modify original
a[0][0] = 0
a[1] = None

print "after", "=>"
print a
print b

输出的结果是:

before =>

[[1], [2], [3]]

[[1], [2], [3]]

after =>

[[0], None, [3]]

[[0], [2], [3]]

测量算法的运行时间:

import time

def procedure():
time.sleep( 2.5 )

# measure process time
t0 = time.clock()
procedure()
print time.clock() - t0, "seconds process time"

# measure wall time
t0 = time.time()
procedure()
print time.time() - t0, "seconds wall time"

循环读文本文件:

import fileinput
import sys
for line in fileinput.input( "../src/hello.xml" ):
sys.stdout.write( "-> " )
sys.stdout.write( line )
import fileinput
import glob
import string, sys

for line in fileinput.input( glob.glob( "../src/hello.xml" ) ):
if fileinput.isfirstline(): # first in a file?
sys.stderr.write( "-- reading %s --\n" % fileinput.filename() )
sys.stdout.write( str( fileinput.lineno() ) + " " + string.upper( line ) )

复制文件的操作:

import os , shutil
print os.listdir( "../src" )

for file in os.listdir( "../src" ):
if os.path.splitext( file )[1] == ".py":
os.mkdir( "../src/back" )
print file
shutil.copy( file, os.path.join( "back", file ) )

可以使用shutil开复制整个目录,然后删除目录

import os , shutil
print os.listdir( ".." )
shutil.copytree("../src", "../src1")
shutil.rmtree( "../src1" )

想内存文件写入内容:

import StringIO

file = StringIO.StringIO()
file.write( "This man is no ordinary man. " )
file.write( "This is Mr. F. G. Superman." )

print file.getvalue()

使用StringIO模块捕获输出:

import StringIO
import string, sys
stdout = sys.stdout
sys.stdout = file = StringIO.StringIO()
print """a"""
sys.stdout = stdout
print string.upper( file.getvalue() )

结果输出A

也可以使用cStringIO:

import cStringIO
file = cStringIO.StringIO( "asdaskdgaksdgkasdja" )
print file.getvalue()
print file.read()

小技巧:由于cStringIO比StringIO的效率高一点,但是兼容性不行,所以可以使用下面的语句:

try:
import cStringIO
StringIO = cStringIO
except ImportError:
import StringIO

print StringIO

类继承的时候构造函数的一点点问题:

class A:
def __init__( self ):
pass
class B( A ):
def __init__( self ):
#A.__init__( self )
super( B, self ).__init__( self )

对字典使用“+”法

import UserDict

class Add( UserDict.UserDict ):
def __init__( self, dict = {}, **kwargs ):
UserDict.UserDict.__init__( self )
self.update( dict )
self.update( kwargs )
def __add__( self, other ):
dict = Add( self.data )
dict.update( other )
return dict

a = Add( a = 1 )
b = Add( b = 2 )
print a + b

输出的结果为:{'a': 1, 'b': 2}

实例类似一个普通的列表对象, 但它允许你通过赋值为列表添加项目.

import UserList

class AutoList( UserList.UserList ):
def __init__( self ):
super( AutoList, self ).__init__( self )
def __setitem__( self, i, item ):
if i == len( self.data ):
self.append( item )
else:
self.data[i] = item

list = AutoList()

for i in range( 10 ):
list[i] = i
print list

输出的结果为:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

随机数:

import random

for i in range(5):

# random float: 0.0 <= number < 1.0
print random.random(),

# random float: 10 <= number < 20
print random.uniform(10, 20),

# random integer: 100 <= number <= 1000
print random.randint(100, 1000),

# random integer: even numbers in 100 <= number < 1000
print random.randrange(100, 1000, 2)

随机打乱序列的顺序:

import random

a = range( 10 )
print a
random.shuffle( a )
print a<span style="font-family: verdana, Arial, Helvetica, sans-serif;" face="verdana, Arial, Helvetica, sans-serif"> <span class="Apple-style-span" style="line-height: 21px; font-size: 14px; white-space: normal;">
</span></span>

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[5, 2, 6, 9, 4, 7, 3, 8, 0, 1]

你的结果可能不一样

>>> os.environ["HOME"]
'C:\\Users\\Administrator'

>>> os.getcwd() #获得当前的目录
'D:\\new'
>>> os.getenv("QTDIR") #获取环境变量的值
'D:\\vs2010-qt-src-4.7.4\\qt-src-4.7.4'
os.putenv(varname, value) #设置环境变量的值

os.mkdir(path[, mode])
>>> os.mkdir("aa")
>>> os.rmdir("aa")
>>>os.makedirs("aa\\bb\\cc") 多级目录
os.removedirs(path)?
os.remove("d:\\new\\hello.txt") #删除文件,如果是目录的话,出错
os.rename("test.txt","a.txt")

random.randint(a, b)
Return a random integer N such that a <= N <= b.
random.choice(seq)
Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.
random.random()
Return the next random floating point number in the range [0.0, 1.0).
random.shuffle(x[, random]) 随机排序序列
random.uniform(a, b)?返回a<=N<=b之间的浮点数
random.randrange([start], stop[, step])想当于choice(range(start, stop, step))
>>> random.random() # Random float x, 0.0 <= x < 1.0
0.37444887175646646
>>> random.uniform(1, 10) # Random float x, 1.0 <= x < 10.0
1.1800146073117523
>>> random.randint(1, 10) # Integer from 1 to 10, endpoints included
7
>>> random.randrange(0, 101, 2) # Even integer from 0 to 100
26
>>> random.choice('abcdefghij') # Choose a random element
'c'

>>> items = [1, 2, 3, 4, 5, 6, 7]
>>> random.shuffle(items)
>>> items
[7, 3, 2, 5, 6, 4, 1]

>>> random.sample([1, 2, 3, 4, 5], 3) # Choose 3 elements
[4, 1, 5]

>>> datetime.MAXYEAR
9999
>>> datetime.MINYEAR
1

>>> a=datetime.date(2011,2,1)
>>> a.today()
datetime.date(2011, 11, 26)
>>> a.year
2011
>>> a.month
2
>>> a.day
1

>>> import time
>>> from datetime import date
>>> today = date.today()
>>> today
datetime.date(2007, 12, 5)
>>> my_birthday = date(today.year, 6, 24)
>>> if my_birthday < today:
... my_birthday = my_birthday.replace(year=today.year + 1)
>>> my_birthday
datetime.date(2008, 6, 24)
>>> time_to_birthday = abs(my_birthday - today) #计算日期之差
>>> time_to_birthday.days
202

>>> datetime.now() #当前时间
datetime.datetime(2011, 11, 26, 10, 40, 10, 283000)
>>> datetime.utcnow()
datetime.datetime(2011, 11, 26, 2, 40, 34, 809000)
>>> a=date(2005,7,14) #日期和时间进行合并
>>> t=time(12,30,12)
>>> datetime.combine(a,t)
datetime.datetime(2005, 7, 14, 12, 30, 12)
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)

>>> from datetime import timedelta, datetime, tzinfo
>>> class GMT1(tzinfo):
... def __init__(self): # DST starts last Sunday in March
... d = datetime(dt.year, 4, 1) # ends last Sunday in October
... self.dston = d - timedelta(days=d.weekday() + 1)
... d = datetime(dt.year, 11, 1)
... self.dstoff = d - timedelta(days=d.weekday() + 1)
... def utcoffset(self, dt):
... return timedelta(hours=1) + self.dst(dt)
... def dst(self, dt):
... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
... return timedelta(hours=1)
... else:
... return timedelta(0)
... def tzname(self,dt):
... return "GMT +1"
...
>>> class GMT2(tzinfo):
... def __init__(self):
... d = datetime(dt.year, 4, 1)
... self.dston = d - timedelta(days=d.weekday() + 1)
... d = datetime(dt.year, 11, 1)
... self.dstoff = d - timedelta(days=d.weekday() + 1)
... def utcoffset(self, dt):
... return timedelta(hours=1) + self.dst(dt)
... def dst(self, dt):
... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
... return timedelta(hours=2)
... else:
... return timedelta(0)
... def tzname(self,dt):
... return "GMT +2"
...
>>> gmt1 = GMT1()
>>> # Daylight Saving Time
>>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
>>> dt1.dst()
datetime.timedelta(0)
>>> dt1.utcoffset()
datetime.timedelta(0, 3600)
>>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
>>> dt2.dst()
datetime.timedelta(0, 3600)
>>> dt2.utcoffset()
datetime.timedelta(0, 7200)
>>> # Convert datetime to another time zone
>>> dt3 = dt2.astimezone(GMT2())
>>> dt3 # doctest: +ELLIPSIS
datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
>>> dt2 # doctest: +ELLIPSIS
datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
>>> dt2.utctimetuple() == dt3.utctimetuple()
True

class datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]])
>>> a=time(10,46,12)
>>> a.min
datetime.time(0, 0)
>>> a.max
datetime.time(23, 59, 59, 999999)
>>> a.hour
10
>>> a.minute
46
>>> a.second
12
>>> a.microsecond
0

class collections.Counter([iterable-or-mapping])
A Counter is a dict subclass for counting hashable objects.
>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
... cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})

>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall('\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]

>>> c = Counter(['eggs', 'ham'])
>>> c['bacon'] # count of a missing element is zero
0
>>> c['sausage'] = 0 # counter entry with a zero count
>>> del c['sausage'] # del actually removes the entry

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']

most_common([n]) #出现次数最多的n个
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> sum(c.values()) # total of all counts
4
>>> list(c)
['a', 'c', 'b', 'd']
>>> set(c)
set(['a', 'c', 'b', 'd'])
>>> dict(c)
{'a': 4, 'c': 0, 'b': 2, 'd': -2}
>>> c.items()
[('a', 4), ('c', 0), ('b', 2), ('d', -2)]
>>> c.most_common()[:-2:-1] # c.most_common()[:-n:-1] n least #common elements

[('d', -2)]
>>> c+=Counter()
>>> c
Counter({'a': 4, 'b': 2})
>>> c.clear()
>>> c
Counter()

>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d # add two counters together: c[x] + d[x]
Counter({'a': 4, 'b': 3})
>>> c - d # subtract (keeping only positive counts)
Counter({'a': 2})
>>> c & d # intersection: min(c[x], d[x])
Counter({'a': 1, 'b': 1})
>>> c | d # union: max(c[x], d[x])
Counter({'a': 3, 'b': 2})

>>> from collections import deque
>>> d = deque('ghi') # make a new deque with three items
>>> for elem in d: # iterate over the deque's elements
... print elem.upper()
G
H
I

>>> d.append('j') # add a new entry to the right side
>>> d.appendleft('f') # add a new entry to the left side
>>> d # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])

>>> d.pop() # return and remove the rightmost item
'j'
>>> d.popleft() # return and remove the leftmost item
'f'
>>> list(d) # list the contents of the deque
['g', 'h', 'i']
>>> d[0] # peek at leftmost item
'g'
>>> d[-1] # peek at rightmost item
'i'

>>> list(reversed(d)) # list the contents of a deque in reverse
['i', 'h', 'g']
>>> 'h' in d # search the deque
True
>>> d.extend('jkl') # add multiple elements at once
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> d.rotate(1) # right rotation
>>> d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
>>> d.rotate(-1) # left rotation
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])

>>> deque(reversed(d)) # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
>>> d.clear() # empty the deque
>>> d.pop() # cannot pop from an empty deque
Traceback (most recent call last):
File "<pyshell#6>", line 1, in -toplevel-
d.pop()
IndexError: pop from an empty deque

>>> d.extendleft('abc') # extendleft() reverses the input order
>>> d
deque(['c', 'b', 'a'])

def tail(filename, n=10):
'Return the last n lines of a file'
return deque(open(filename), n)

def moving_average(iterable, n=3):
# moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
# http://en.wikipedia.org/wiki/Moving_average
it = iter(iterable)
d = deque(itertools.islice(it, n-1))
d.appendleft(0)
s = sum(d)
for elem in it:
s += elem - d.popleft()
d.append(elem)
yield s / float(n)

def delete_nth(d, n):
d.rotate(-n)
d.popleft()
d.rotate(n)

class collections.defaultdict([default_factory[, ...]])
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

>>> d = {}
>>> for k, v in s:
... d.setdefault(k, []).append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]

>>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
>>> d = defaultdict(set)
>>> for k, v in s:
... d[k].add(v)
...
>>> d.items()
[('blue', set([2, 4])), ('red', set([1, 3]))]

>>> def heapsort(iterable):
... 'Equivalent to sorted(iterable)'
... h = []
... for value in iterable:
... heappush(h, value)
... return [heappop(h) for i in range(len(h))]
...
>>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> h = []
>>> heappush(h, (5, 'write code'))
>>> heappush(h, (7, 'release product'))
>>> heappush(h, (1, 'write spec'))
>>> heappush(h, (3, 'create tests'))
>>> heappop(h)
(1, 'write spec')

#coding=utf-8
#堆的实例

from heapq import heappush, heappop, heappushpop, heapify, heapreplace, nlargest,\
nsmallest

heap=[]

heappush(heap,"A");
heappush(heap,"C");
heappush(heap,"B");

print heap

heappop(heap) #弹出堆中最小的元素
print heap

var=heappushpop(heap,"D") #返回并弹出堆中最小的元素,并且将D压入堆
print var
print heap

var=heapreplace(heap,"E") #返回并弹出堆中最小的元素,并且将D压入堆,
print var
print heap

list=[1,2,3,4,5,6,7,8,9,0]
heapify(list);
print list

print nlargest(3,list) #返回堆中最大的3个
print nsmallest(3,list) #返回堆中最小的3个

---bisect — Array bisection algorithm


#coding=utf-8

import bisect

list=[1,2,3,4,6,7,8,9] #假定list已经排序
print bisect.bisect_left(list,5) #返回5应该插入的索引位置

print bisect.bisect_right(list, 5)

print bisect.bisect(list,5)

bisect.insort_left(list, 5, 0, len(list))
print list

bisect.insort_right(list, 5)
print list

def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError

def find_lt(a, x):
'Find rightmost value less than x'
i = bisect_left(a, x)
if i:
return a[i-1]
raise ValueError

def find_le(a, x):
'Find rightmost value less than or equal to x'
i = bisect_right(a, x)
if i:
return a[i-1]
raise ValueError

def find_gt(a, x):
'Find leftmost value greater than x'
i = bisect_right(a, x)
if i != len(a):
return a[i]
raise ValueError

def find_ge(a, x):
'Find leftmost item greater than or equal to x'
i = bisect_left(a, x)
if i != len(a):
return a[i]
raise ValueError

>>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
... i = bisect(breakpoints, score)
... return grades[i]
...
>>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
['F', 'A', 'C', 'C', 'B', 'A', 'A']

>>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]
>>> data.sort(key=lambda r: r[1])
>>> keys = [r[1] for r in data] # precomputed list of keys
>>> data[bisect_left(keys, 0)]
('black', 0)
>>> data[bisect_left(keys, 1)]
('blue', 1)
>>> data[bisect_left(keys, 5)]
('red', 5)
>>> data[bisect_left(keys, 8)]
('yellow', 8)

使用 apply 函数

def function(a, b):
print a, b
apply(function, ("whither", "canada?"))
apply(function, (1, 2 + 3))
whither canada?
1 5

使用 apply 函数传递关键字参数

def function(a, b):
print a, b

apply(function, ("crunchy", "frog"))
apply(function, ("crunchy",), {"b": "frog"})
apply(function, (), {"a": "crunchy", "b": "frog"})

crunchy frog
crunchy frog
crunchy frog

使用 apply 函数调用基类的构造函数

class Rectangle:
def _ _init_ _(self, color="white", width=10, height=10):
print "create a", color, self, "sized", width, "x", height

class RoundedRectangle(Rectangle):
def _ _init_ _(self, **kw):
apply(Rectangle._ _init_ _, (self,), kw)

rect = Rectangle(color="green", height=100, width=100)
rect = RoundedRectangle(color="blue", height=20)

create a green <Rectangle instance at 8c8260> sized 100 x 100
create a blue <RoundedRectangle instance at 8c84c0> sized 10 x 20

使用 _ _import_ _ 函数获得特定函数

def getfunctionbyname(module_name, function_name):
module = _ _import_ _(module_name)
return getattr(module, function_name)

print repr(getfunctionbyname("dumbdbm", "open"))

<function open at 794fa0>

使用 _ _import_ _ 函数实现 延迟导入

class LazyImport:
def _ _init_ _(self, module_name):
self.module_name = module_name
self.module = None
def _ _getattr_ _(self, name):
if self.module is None:
self.module = _ _import_ _(self.module_name)
return getattr(self.module, name)

string = LazyImport("string")

print string.lowercase

abcdefghijklmnopqrstuvwxyz

使用 dir 函数

def dump(value):
print value, "=>", dir(value)

import sys

dump(0)
dump(1.0)
dump(0.0j) # complex number
dump([]) # list
dump({}) # dictionary
dump("string")
dump(len) # function
dump(sys) # module

0 => []
1.0 => []
0j => ['conjugate', 'imag', 'real']
[] => ['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
{} => ['clear', 'copy', 'get', 'has_key', 'items',
'keys', 'update', 'values']
string => []
<built-in function len> => ['_ _doc_ _', '_ _name_ _', '_ _self_ _']
<module 'sys' (built-in)> => ['_ _doc_ _', '_ _name_ _',
'_ _stderr_ _', '_ _stdin_ _', '_ _stdout_ _', 'argv',
'builtin_module_names', 'copyright', 'dllhandle',
'exc_info', 'exc_type', 'exec_prefix', 'executable',
...

使用 dir 函数查找类的所有成员

class A:
def a(self):
pass
def b(self):
pass

class B(A):
def c(self):
pass
def d(self):
pass

def getmembers(klass, members=None):
# get a list of all class members, ordered by class
if members is None:
members = []
for k in klass._ _bases_ _:
getmembers(k, members)
for m in dir(klass):
if m not in members:
members.append(m)
return members

print getmembers(A)
print getmembers(B)
print getmembers(IOError)

['_ _doc_ _', '_ _module_ _', 'a', 'b']
['_ _doc_ _', '_ _module_ _', 'a', 'b', 'c', 'd']
['_ _doc_ _', '_ _getitem_ _', '_ _init_ _', '_ _module_ _', '_ _str_ _']

 

使用 callable 函数


def dump(function):
if callable(function):
print function, "is callable"
else:
print function, "is *not* callable"

class A:
def method(self, value):
return value

class B(A):
def _ _call_ _(self, value):
return value

a = A()
b = B()

dump(0) # simple objects
dump("string")
dump(callable)
dump(dump) # function

dump(A) # classes
dump(B)
dump(B.method)

dump(a) # instances
dump(b)
dump(b.method)

0 is *not* callable
string is *not* callable
<built-in function callable> is callable
<function dump at 8ca320> is callable
A is callable
B is callable
<unbound method A.method> is callable
<A instance at 8caa10> is *not* callable
<B instance at 8cab00> is callable
<method A.method of B instance at 8cab00> is callable

使用 eval 函数

def dump(expression):
result = eval(expression)
print expression, "=>", result, type(result)

dump("1")
dump("1.0")
dump("'string'")
dump("1.0 + 2.0")
dump("'*' * 10")
dump("len('world')")

1 => 1 <type 'int'>
1.0 => 1.0 <type 'float'>
'string' => string <type 'string'>
1.0 + 2.0 => 3.0 <type 'float'>
'*' * 10 => ********** <type 'string'>
len('world') => 5 <type 'int'>

使用 eval 函数执行任意命令

print eval("_ _import_ _('os').getcwd()")
print eval("_ _import_ _('os').remove('file')")

/home/fredrik/librarybook
Traceback (innermost last):
File "builtin-eval-example-2", line 2, in ?
File "<string>", line 0, in ?
os.error: (2, 'No such file or directory')

使用 compile 函数检查语法


NAME = "script.py"

BODY = """
prnt 'owl-stretching time'
"""

try:
compile(BODY, NAME, "exec")
except SyntaxError, v:
print "syntax error:", v, "in", NAME

# syntax error: invalid syntax in script.py


?


执行已编译的代码


?


BODY = """
print 'the ant, an introduction'
"""

code = compile(BODY, "<script>", "exec")

print code

exec code

<code object ? at 8c6be0, file "<script>", line 0>
the ant, an introduction

 
 
分享到
 
 
     


中国移动 网络规划与管理
医院安防系统远程探视方案解析
基于RFID技术的物联网研究
基于物联网、云计算架构...
基于RFID技术物联网研究与应用
物联网的发展瓶颈和关键技术