Python 允许你实时地创建函数参数列表. 只要把所有的参数放入一个元组中,然后通过内建的 apply 函数调用函数.
In [8]:
def function(a,b):
print a, b
In [9]:
apply(function, ("wheather", "Canada?"))
In [3]:
apply(function, (1, 3+5))
效果等同于:
In [4]:
function("wheather", "Canada?")
In [5]:
function(1, 3+5)
那为什么要使用apply呢?
In [10]:
apply(function, (), {"a":"35cm", "b":"12cm"})
In [16]:
apply(function, ("v",), {"b":"love"})
In [21]:
apply(function, ( ,"v"), {"a":"hello"})
何谓“关键字参数”?
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)
In [34]:
rect = RoundRectangle(color="brown", width=20, height=15)
第二个函数不知道如何使用 ????
修改,子类要以父类为参数!!!
In [41]:
class RoundRectangle(Rectangle):
def __init__(self, **kw):
apply(Rectangle.__init__, (self,), kw)
In [42]:
rect2 = RoundRectangle(color= "blue", width=23, height=10)
使用 * 来标记元组, ** 来标记字典.
apply的第一个参数是函数名,第二个参数是元组,第三个参数是字典。所以用上面这个表达最好不过。
In [39]:
args = ("er",)
kwargs = {"b":"haha"}
function(*args, **kwargs)
In [40]:
apply(function, args, kwargs)
以上等价。
用这个意思引申:
In [44]:
kw = {"color":"brown", "width":123, "height": 34}
rect3 = RoundRectangle(**kw)
In [45]:
rect4 = Rectangle(**kw)
In [46]:
arg=("yellow", 45, 23)
rect5 = Rectangle(*arg)
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
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"))
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
In [17]:
cwd = os.getcwd()
In [18]:
print 1, cwd
In [19]:
os.chdir("samples")
In [20]:
print 2, os.getcwd()
In [22]:
os.chdir(os.pardir)
print 3, os.getcwd()
In [ ]:
In [53]:
import stat
In [55]:
import os, time
In [67]:
st = os.stat("samples/sample.txt")
os.stat是将文件的相关属性读出来,然后用stat模块来处理,处理方式有多重,就要看看stat提供了什么了。
In [ ]:
In [1]:
import string
In [60]:
text = "Monty Python's Flying Circus"
In [61]:
print "upper", "=>", string.upper(text)
In [62]:
print "lower", "=>", string.lower(text)
In [63]:
print "split", "=>", string.split(text)
分列变成了list
In [64]:
print "join", "=>", string.join(string.split(text))
join和split相反。
In [65]:
print "replace", "=>", string.replace(text, "Python", "Cplus")
replace的参数结构是:
In [66]:
print "find", "=>", string.find(text, "Python")
In [67]:
print "find", "=>", string.find(text, "Python"), string.find(text, "Cplus")
In [68]:
print text
上面replace的结果,没有影响原始的text。
find时,能找到就显示位置,不能找到就显示-1
In [70]:
print "count", "=>", string.count(text,"n")
和数学运算一样,这些方法也分一元的和多元的:
upper, lower, split, join 都是一元的。其中join的对象是一个list。
replace, find, count则需要除了text之外的参数。replace需要额外两个,用以指明替换关系。find只需要一个被查找对象。count则需要一个需要计数的字符。
特别注意: replace不影响原始字符串对象。(好奇怪)
In [2]:
print string.atoi("23")
In [3]:
type(string.atoi("23"))
Out[3]:
In [4]:
int("234")
Out[4]:
In [5]:
type(int("234"))
Out[5]:
In [6]:
type(float("334"))
Out[6]:
In [7]:
float("334")
Out[7]:
In [8]:
string.atof("456")
Out[8]:
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))
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [9]:
import math
In [10]:
math.pi
Out[10]:
In [11]:
math.e
Out[11]:
In [12]:
print math.hypot(3,4)
In [13]:
math.sqrt(25)
Out[13]:
In [14]:
import cmath
In [15]:
print cmath.sqrt(-1)
In [16]:
import operator
In [18]:
operator.add(3,5)
Out[18]:
In [19]:
seq = 1,5,7,9
In [22]:
reduce(operator.add,seq)
Out[22]:
In [23]:
reduce(operator.sub, seq)
Out[23]:
In [24]:
reduce(operator.mul, seq)
Out[24]:
In [26]:
float(reduce(operator.div, seq))
Out[26]:
operator下的这四则运算,都是针对两个数进行的,即参数只能是两个。为了能对多个数进行连续运算,就需要用reduce,它的意思是两个运算后,作为一个数,与下一个继续进行两个数运算,直到数列终。感觉和apply作用有点差不多,第一个参数是函数,第二个参数是数列(具体参数)。
In [27]:
operator.concat("ert", "erui")
Out[27]:
In [28]:
operator.getitem(seq,1)
Out[28]:
In [29]:
operator.indexOf(seq, 5)
Out[29]:
getitem和indexOf为一对逆运算,前者求指定位置上的值,后者求给定值的位置。注意,后者是大写的字母o。
In [31]:
operator.sequenceIncludes(seq, 5)
Out[31]:
判断序列中是否包含某个值。结果是布尔值。
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)
In [41]:
dump([3,4,5,6])
In [42]:
dump("weioiuernj")
In [43]:
dump({"a":"155cm", "b":"187cm"})
In [44]:
dump(len)
In [45]:
dump(UserList)
In [46]:
dump(UserList.UserList)
In [47]:
dump(UserList.UserList())
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)
In [6]:
check(0.0)
In [7]:
check("picklecai")
In [8]:
class A:
pass
In [9]:
check(A)
In [10]:
a = A()
In [11]:
check(a)
types 模块在第一次引入的时候会破坏当前的异常状态. 也就是说, 不要在异常处理语句块中导入该模块 ( 或其他会导入它的模块 ) .
In [ ]:
In [ ]:
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]:
In [ ]: