1. compile
#!/usr/bin/env python
eval_code = compile("100 + 200", "", "eval")
print eval(eval_code)
single_code = compile("print 'Hello World'", '', "single")
exec single_code
exec_code = compile("""
req = input('Count how many numbers?')
for eachNum in range(req):
print eachNum
""", '','exec')
exec exec_code
2.
#! /usr/bin/env python
def foo():
return True
def bar():
'bar() does not much'
return True
foo.__doc__ = 'foo() does not do much'
foo.tester = '''
if foo():
print 'PASSED'
else:
print 'FAILED'
'''
for eachAttr in dir():
obj = eval(eachAttr) #convert the string to the object
if isinstance(obj, type(foo)):
if hasattr(obj, '__doc__'):
print '\n Function "%s" has a doc string:\n\t%s' %(eachAttr, obj.__doc__)
if hasattr(obj, 'tester'):
print 'Function "%s" has a tester...executing ' %eachAttr
exec obj.tester #to execute the strings
else:
print 'Funciton "%s" has no tester...skipping' %eachAttr
else:
print '"%s" is not a Function' %eachAttr
print '________________dir()__________________'
print dir()
3.
globals/locals/execfile/
4.
try:
_count = int(open("counter").read())
except IOError:
_count = 0
def incrcounter(n):
global _count
_count = _count + n
def savecounter():
open("counter", "w").write("%d" % _count)
import atexit
atexit.register(savecounter)
5.
>>> m = re.findall(r'(the)(dog)' , 'bite thedog thedog')
>>> m
[('the', 'dog'), ('the', 'dog')]
>>>
6.
>>> patt = '^((\w){3}(\d+))(BB)'
>>> m = re.match(patt, 'THU34324BB')
>>> m.groups()
('THU34324', 'U', '34324', 'BB')
>>>
7.
一个解决办法是用“非贪婪”操作符,“?”. 这个操作符可以用在 “*”, “+”, 或 “?” 的
后面。它的作用是要求正则表达式引擎匹配的字符越少越好。因此,如果我们把“?”放在“.+”
的后面,我们就得到了想要的结果,
>>> patt = '.+?(\d+-\d+-\d+)'
>>> re.match(patt, data).group(1) # subgroup 1 # 子组 1
'1171590364-6-8'
8.
Variable length parameter
#coding:utf-8
def foo(arg1,arg2="OK",*tupleArg,**dictArg):
print "arg1=",arg1
print "arg2=",arg2
for i,element in enumerate(tupleArg):
print "tupleArg %d-->%s" % (i,str(element))
for key in dictArg:
print "dictArg %s-->%s" %(key,dictArg[key])
myList=["my1","my2"]
myDict={"name":"Tom","age":22}
foo("formal_args",arg2="argSecond",a = 2) #a = 2 is assigned to dictArg
print "*"*40
foo(123,myList,myDict) # because there is no * or **, so this is the common assignment.
print "*"*40
foo(123,rt=123,*myList,**myDict) #this is no rt, so rt belongs to dictArg
-------------------
output:
arg1= formal_args
arg2= argSecond
dictArg a-->2
****************************************
arg1= 123
arg2= ['my1', 'my2']
tupleArg 0-->{'age': 22, 'name': 'Tom'}
****************************************
arg1= 123
arg2= my1
tupleArg 0-->my2
dictArg rt-->123
dictArg age-->22
dictArg name-->Tom
[Finished in 0.1s]
9.
Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
This will print
[1]
[1, 2]
[1, 2, 3]
10.
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43