Python 允许函数参数有缺省值;如果调用函数时不使用参数,参数将获得它的缺省值。此外,通过使用命名参数还可以以任意顺序指定参数。SQL Server Transact/SQL 中的存储过程也可以做到这些;如果你是脚本高手,你可以略过这部分。
info 函数就是这样一个例子,它有两个可选参数。
'''test default value for argument'''
def info(a, arg1=0, arg2=4):
print "==========================info method==================="
print "a is %s, agr1 is %d, arg2 is %d" % (a, arg1, arg2)
#print a 's type : int or str
print type(a)
调用:
import him
him.info(1)
him.info(1,2)
him.info("555",2,47)
type 函数
type 函数返回任意对象的数据类型。在 types 模块中列出了可能的数据类型。这对于处理多种数据类型的帮助者函数 非常有用。
import him
him.info(1)
him.info(1,2)
him.info("555",2,47)
print type(him)
'''getattr() methond test'''
def getattrTest():
print "==========================getattrTest method==================="
li = ['test1', 'test2']
#get the pop method
print getattr(li, 'pop')
##error no pop2 method
##print getattr(li, 'pop2')
##get the append methond and pass to conference
xp = getattr(li, 'append')
## in fact, xp is append method ,methods are also object in python
xp('test3')
##length + 1
print "list length is %d" % len(li)
print li
[mapping-expression for element in source-list if filter-expression]
这是你所知所爱的列表解析的扩展。前三部分都是相同的;最后一部分,以 if 开头的是过滤器表达式。过滤器表达式可以是返回值为真或者假的任何表达式 。任何经过滤器表达式演算值为真的元素都可以包含在映射中。其它的元素都将忽略,它们不会进入映射表达式,更不会包含在输出列表中。
def filterList():
print "==========================filterList method==================="
li = ["a","23","this is","bb"]
print li
print [elem for elem in li if(elem)!="a" ]
##return also a list
print [elem for elem in li if len(elem)==2]
调用代码:
import him
him.info(1)
him.info(1,2)
him.info("555",2,47)
print type(him)
him.getattrTest()
him.filterList()
him.andorTest()