pengjunling 发表于 2017-4-22 09:58:24

Python学习第四天-Python中的自省

  Python 中万物皆对象,自省是指代码可以查看内存中以对象形式存在的其它模块和函数,获取它们的信息,并对它们进行操作。用这种方法,你可以定义没有名称的函数,不按函数声明的参数顺序调用函数,甚至引用事先并不知道名称的函数。
  
使用可选参数和命名参数
  


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 介绍
  你已经知道 Python 函数是对象。你不知道的是,使用 getattr 函数,可以得到一个直到运行时才知道名称的函数的引用。
  


'''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

   


过滤列表
  


如你所知,Python 具有通过列表解析将列表映射到其它列表的强大能力。这种能力同过滤机制结合使用,使列表中的有些元素被映射的同时跳过另外一些元素。



过滤列表语法:

[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
##return also a list
print

   调用代码:
  


import him
him.info(1)
him.info(1,2)
him.info("555",2,47)
print type(him)
him.getattrTest()
him.filterList()
him.andorTest()
 
页: [1]
查看完整版本: Python学习第四天-Python中的自省